我正在使用R编程语言。假设我有以下数据集:
a = rnorm(10,10,10)
b = rnorm(10, 6, 7)
c = rnorm( 10, 5, 5)
d = data.frame(a,b,c)
head(d)
a b c
1 18.3615091 -1.1253320 0.3403199
2 4.9365020 2.4014072 -3.5771919
3 12.5686200 0.7474177 -4.6788551
4 0.1913607 -0.6456205 3.8693564
5 9.1718179 16.1776224 8.1820692
6 18.3757202 4.1313655 -0.4195688
是否可以将此数据集转换为单列数据(即1列和30行)?
我尝试了几种方法:
#first way
d = data.frame(a + b + c)
#second way
d = cbind(a,b,c)
#third way
d = rbind(a,b,c)
但是似乎什么都不起作用。
谁能告诉我怎么做这个?
感谢您可以首先将数据帧转换为矩阵。R中的矩阵以列为主的顺序存储,因此(*)如果将矩阵转换为向量,则将得到堆叠的列作为向量:
as.vector(as.matrix(d))
如果你想要dataframe:
data.frame(stack = as.vector(as.matrix(d)))
(*)在R中,矩阵只是一个带有维度属性的向量,数据在向量中以列为主的顺序存储。例如:
structure(1:4, dim = c(2, 2))
[,1] [,2]
[1,] 1 3
[2,] 2 4
当你把一个矩阵转换成一个向量时,你只需要去掉维数。
as.vector(.Last.value)
[1] 1 2 3 4
您可以尝试stack
或reshape2::melt
或tidyr::pivot_longer
stack(d)
reshape2::melt(d)
tidyr::pivot_longer(c(a,b,c))
。