最好的方式转置data.table [英] best way to transpose data.table
本文介绍了最好的方式转置data.table的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经常需要转置一个 data.table
,每次它需要几行代码,我想知道是否有任何比我更好的解决方案。
I often need to transpose a data.table
, every time it takes several lines of code and I am wondering if there's any better solution than mine.
如果我们使用示例表
library(data.table)
mydata <- data.table(col0=c("row1","row2","row3"),
col1=c(11,21,31),
col2=c(12,22,32),
col3=c(13,23,33))
mydata
# col0 col1 col2 col3
# row1 11 12 13
# row2 21 22 23
# row3 31 32 33
用 t()
转置它,它将转换为转换为字符
类型的矩阵,而应用 data.table
到此矩阵将失去 row.names
:
and just transpose it with t()
, it will be transposed to the matrix with conversion to character
type, while applying data.table
to such matrix will lose row.names
:
t(mydata)
# [,1] [,2] [,3]
# col0 "row1" "row2" "row3"
# col1 "11" "21" "31"
# col2 "12" "22" "32"
# col3 "13" "23" "33"
data.table(t(mydata))
# V1 V2 V3
# row1 row2 row3
# 11 21 31
# 12 22 32
# 13 23 33
所以我必须为此写一个函数:
so I had to write a function for this:
tdt <- function(inpdt){
transposed <- t(inpdt[,-1,with=F]);
colnames(transposed) <- inpdt[[1]];
transposed <- data.table(transposed, keep.rownames=T);
setnames(transposed, 1, names(inpdt)[1]);
return(transposed);
}
tdt(mydata)
# col0 row1 row2 row3
# col1 11 21 31
# col2 12 22 32
# col3 13 23 33
有什么我可以在这里优化或以更好的方式? p>
is there anything I could optimize here or do it in "nicer" way?
推荐答案
为什么不只是熔化
和 dcast
data.table
?
library(reshape2)
dcast.data.table(melt(mydata, id.vars = "col0"), variable ~ col0)
# variable row1 row2 row3
# 1: col1 11 21 31
# 2: col2 12 22 32
# 3: col3 13 23 33
这篇关于最好的方式转置data.table的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文