需要将列转换为 R 中的行 [英] Need to convert columns to rows in R

查看:41
本文介绍了需要将列转换为 R 中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的数据

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 转换为 matrixmelt 为 '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 中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆