📜  如何在 R 中转置 DataFrame?

📅  最后修改于: 2022-05-13 01:54:53.298000             🧑  作者: Mango

如何在 R 中转置 DataFrame?

在本文中,我们将讨论如何在 R 编程语言中转置数据帧。转置意味着将行转换为列,将列转换为行

创建数据框进行演示:

R
# create a dataframe
data = data.frame(col1=c(1:5),
                  col2=c(6:10),
                  col3=c(11:15),
                  col4=c(16:20))
  
# assign row names to dataframe
row.names(data) = c("r1","r2","r3","r4","r5")
  
# display
data


R
# create a dataframe
data = data.frame(col1 = c(1:5), 
                  col2 = c(6:10),
                  col3 = c(11:15),
                  col4 = c(16:20))
  
# assign row names to dataframe
row.names(data) = c("r1","r2","r3",
                    "r4","r5")
  
# display transposed dataframe
t(data)


R
# load module
library(data.table)
  
# create a dataframe
data = data.frame(col1=c(1:5),
                  col2=c(6:10),
                  col3=c(11:15),
                  col4=c(16:20))
  
# assign row names to dataframe
row.names(data) = c("r1","r2","r3","r4","r5")
  
# display transposed dataframe
# using data.table
transpose(data)


输出:

col1 col2 col3 col4
r1    1    6   11   16
r2    2    7   12   17
r3    3    8   13   18
r4    4    9   14   19
r5    5   10   15   20

方法一:使用 t()函数

这里我们使用 t()函数,它代表 transpose 来转置数据帧

例子:

R

# create a dataframe
data = data.frame(col1 = c(1:5), 
                  col2 = c(6:10),
                  col3 = c(11:15),
                  col4 = c(16:20))
  
# assign row names to dataframe
row.names(data) = c("r1","r2","r3",
                    "r4","r5")
  
# display transposed dataframe
t(data)

输出:

r1 r2 r3 r4 r5
col1  1  2  3  4  5
col2  6  7  8  9 10
col3 11 12 13 14 15
col4 16 17 18 19 20

方法2:使用data.table转置数据框

这里我们使用 data.table 数据结构来转置数据帧,我们使用 transpose() 方法来做到这一点

例子:

R

# load module
library(data.table)
  
# create a dataframe
data = data.frame(col1=c(1:5),
                  col2=c(6:10),
                  col3=c(11:15),
                  col4=c(16:20))
  
# assign row names to dataframe
row.names(data) = c("r1","r2","r3","r4","r5")
  
# display transposed dataframe
# using data.table
transpose(data)

输出:

V1 V2 V3 V4 V5
1  1  2  3  4  5
2  6  7  8  9 10
3 11 12 13 14 15
4 16 17 18 19 20