问题描述
我有类似的数据
a b c
1 5 4
3 6 1
2 5 3
我想将其转换为将所有列转换为行并想要像
I want to convert it to convert all the columns to rows and want an output like
r1 r2 r3 r4
a 1 3 2
b 5 6 5
c 4 1 3
提前致谢
推荐答案
我们可以转置数据集并转换为data.frame
,第一列作为行名.
We can transpose the dataset and convert to data.frame
with the first column as the row names.
m1 <- t(df1)
d2 <- data.frame(r1= row.names(m1), m1, row.names=NULL)
在 data.frame
调用中包含 row.names
参数(来自@Richard Scriven 的评论)
Included the row.names
argument in the data.frame
call (from @Richard Scriven's comment)
或者正如@Ananda Mahto 提到的,我们可以使用 names(df1)
来创建 'r1' 列,从而跳过在全局环境中创建对象.
Or as @Ananda Mahto mentioned, we can use names(df1)
to create the 'r1' column, thereby skipping the creation of an object in the global environment.
d2 <- data.frame(r1=names(df1), t(df1))
或者另一个选项是 melt/dcast
.我们将 data.frame
转换为 matrix
,melt
为 'long' 格式,然后 dcast
将其转换为 'wide' 格式.
Or another option is melt/dcast
. We convert the data.frame
to matrix
, melt
to 'long' format and then dcast
it to 'wide' format.
library(reshape2)
dcast(melt(as.matrix(df1)), Var2~paste0('r', Var1), value.var='value')
这篇关于需要将列转换为 R 中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!