"pile" 列彼此重叠
"pile" columns on top of each other
我正在使用 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)
但似乎没有任何效果。
有人可以告诉我怎么做吗?
谢谢
您可以尝试 stack
或 reshape2::melt
或 tidyr::pivot_longer
stack(d)
reshape2::melt(d)
tidyr::pivot_longer(c(a,b,c))
会起作用。
您可以先将数据帧转换为矩阵。 R 中的矩阵存储在 column-major order 中,因此 (*) 如果您将矩阵转换为向量,您将得到堆叠的列作为向量:
as.vector(as.matrix(d))
如果你想要数据框:
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
我正在使用 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)
但似乎没有任何效果。
有人可以告诉我怎么做吗?
谢谢
您可以尝试 stack
或 reshape2::melt
或 tidyr::pivot_longer
stack(d)
reshape2::melt(d)
tidyr::pivot_longer(c(a,b,c))
会起作用。
您可以先将数据帧转换为矩阵。 R 中的矩阵存储在 column-major order 中,因此 (*) 如果您将矩阵转换为向量,您将得到堆叠的列作为向量:
as.vector(as.matrix(d))
如果你想要数据框:
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