由于data.frame
s本质上是列的列表,因此unlist(df1)
将为您提供所有值的一个大向量.现在你可以简单地data.frame
从中构造一个新的:
data.frame(col = unlist(df1))
Run Code Online (Sandbox Code Playgroud)
如果你想要一个指标:
stack(df1)
# values ind
# 1 1 col1
# 2 2 col1
# 3 3 col1
# 4 4 col2
# 5 5 col2
# 6 6 col2
# 7 7 col3
# 8 8 col3
# 9 9 col3
Run Code Online (Sandbox Code Playgroud)
只是为了提供一套完整的方法,这就是tidyr
方法.
library(tidyr)
gather(df1)
key value
1 col1 1
2 col1 2
3 col1 3
4 col2 4
5 col2 5
6 col2 6
7 col3 7
8 col3 8
9 col3 9
Run Code Online (Sandbox Code Playgroud)
还有一个使用c
功能:
data.frame(col11 = c(df1,recursive=TRUE))
col11
col11 1
col12 2
col13 3
col21 4
col22 5
col23 6
col31 7
col32 8
col33 9
Run Code Online (Sandbox Code Playgroud)
你可以尝试:
as.data.frame(as.vector(as.matrix(df1)))
# as.vector(as.matrix(df1))
#1 1
#2 2
#3 3
#4 4
#5 5
#6 6
#7 7
#8 8
#9 9
Run Code Online (Sandbox Code Playgroud)