如何转置 R data.table?为什么 t() 不起作用?
How does one take the transpose of an R data.table? Why doesn't t() work?
我有以下R data.table
library(data.table)
mtcars = as.data.table(mtcars)
dt = colSums(mtcars)
> dt
mpg cyl disp hp drat wt qsec vs
642.900 198.000 7383.100 4694.000 115.090 102.952 571.160 14.000
am gear carb
13.000 118.000 90.000
我想按如下方式重塑 data.table dt
:
> transpose
column1 column2
mpg 642.900
cyl 198.000
disp 7373.100
hp 4694.000
drat 115.090
wt 102.952
qsec 571.160
vs 14.000
am 13.000
gear 118.000
carb 90.000
函数 t()
似乎没有按预期工作。
transpose = t(dt)
我怀疑使用 melt()
和 dcast()
可以快速完成此操作,但我不确定如何定义每一列,即 column1
和 column2
我发现这个有效:
df = as.data.table(t(as.matrix(dt)))
它甚至保留了名字
一个dplyr
解决方案:
library(dplyr)
library(data.table)
mtcars <- data.table(mtcars) # make data.table
class(mtcars) # check that it is a data.table
mtcars %>% # take the data.table
summarise_all(funs(sum)) %>% # get the sum of each column
gather(variable, sum) # gather all columns
gather
、spread
和 summarise
是我进行所有移调的方式。 "Variable" 和 "sum" 成为新的列名:
variable sum
1 mpg 642.900
2 cyl 198.000
3 disp 7383.100
4 hp 4694.000
5 drat 115.090
6 wt 102.952
7 qsec 571.160
8 vs 14.000
9 am 13.000
10 gear 118.000
11 carb 90.000
我有以下R data.table
library(data.table)
mtcars = as.data.table(mtcars)
dt = colSums(mtcars)
> dt
mpg cyl disp hp drat wt qsec vs
642.900 198.000 7383.100 4694.000 115.090 102.952 571.160 14.000
am gear carb
13.000 118.000 90.000
我想按如下方式重塑 data.table dt
:
> transpose
column1 column2
mpg 642.900
cyl 198.000
disp 7373.100
hp 4694.000
drat 115.090
wt 102.952
qsec 571.160
vs 14.000
am 13.000
gear 118.000
carb 90.000
函数 t()
似乎没有按预期工作。
transpose = t(dt)
我怀疑使用 melt()
和 dcast()
可以快速完成此操作,但我不确定如何定义每一列,即 column1
和 column2
我发现这个有效:
df = as.data.table(t(as.matrix(dt)))
它甚至保留了名字
一个dplyr
解决方案:
library(dplyr)
library(data.table)
mtcars <- data.table(mtcars) # make data.table
class(mtcars) # check that it is a data.table
mtcars %>% # take the data.table
summarise_all(funs(sum)) %>% # get the sum of each column
gather(variable, sum) # gather all columns
gather
、spread
和 summarise
是我进行所有移调的方式。 "Variable" 和 "sum" 成为新的列名:
variable sum
1 mpg 642.900
2 cyl 198.000
3 disp 7383.100
4 hp 4694.000
5 drat 115.090
6 wt 102.952
7 qsec 571.160
8 vs 14.000
9 am 13.000
10 gear 118.000
11 carb 90.000