使用R将行转换为列和列

时间:2021-02-14 04:38:41

I have a dataframe with unique row names and unique column names. I want to convert the rows into columns and column into rows.

我有一个具有唯一行名和唯一列名的数据框。我想将行转换为列,将列转换为行。

For example, this code:

例如,这段代码:

starting_df <- data.frame(row.names= c(LETTERS[1:4]),
                          a = c(1:4),
                          b = seq(0.02,0.08,by=0.02),
                          c = c("Aaaa","Bbbb","Cccc","Dddd")
                )

results in the following:

结果如下:

> starting_df
  a    b    c
A 1 0.02 Aaaa
B 2 0.04 Bbbb
C 3 0.06 Cccc
D 4 0.08 Dddd

I want to convert it into another data frame containing exactly the same data, except that what were formerly rows were now columns and vice versa:

我想将它转换为包含完全相同数据的另一个数据框,除了之前的行现在是列,反之亦然:

> final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

1 个解决方案

#1


18  

Simply use the base transpose function t, wrapped with as.data.frame:

只需使用as.data.frame包装的基本转置函数t:

final_df <- as.data.frame(t(starting_df))
final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with as.data.frame gets back a data frame instead of a matrix. Thanks!

以上更新。正如docendo discimus指出的那样,t返回一个矩阵。正如Mark建议用as.data.frame包装它,得到一个数据帧而不是矩阵。谢谢!

#1


18  

Simply use the base transpose function t, wrapped with as.data.frame:

只需使用as.data.frame包装的基本转置函数t:

final_df <- as.data.frame(t(starting_df))
final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with as.data.frame gets back a data frame instead of a matrix. Thanks!

以上更新。正如docendo discimus指出的那样,t返回一个矩阵。正如Mark建议用as.data.frame包装它,得到一个数据帧而不是矩阵。谢谢!