数据透视表类似于重塑熔化函数 [英] Pivot on data.table similar to rehape melt function
问题描述
我已经读了一些引用类似的问题在这里SO,但是还没有能够找到一个解决方案,并想知道是否有任何方法做以下使用只是data.table。
I have read some references to similar problems here on SO, but haven't been able to find a solution yet and wondering if there is any way to do the following using just data.table.
我将使用一个简化的例子,但在实践中,我的数据表有> 1000列类似于var1,var2,... var1000等。
I'll use a simplified example, but in practice, my data table has > 1000 columns similar to var1, var2, ... var1000, etc.
dt <- data.table(uid=c("a","b"), var1=c(1,2), var2=c(100,200))
我正在寻找一个解决方案,这将允许我得到类似于reshape的熔化函数的输出 - -
I am looking for a solution that will allow me to get an output similar to reshape's melt function --
> melt(dt, id=c("uid"))
uid variable value
1 a var1 1
2 b var1 2
3 a var2 100
4 b var2 200
也就是说,除了uid之外的所有列都列在具有相应值在邻接的列中。我已经尝试这个与列表等的组合,但可能会缺少一些显而易见的东西。
That is, all the columns except for uid are listed under a single column with the corresponding values in an adjoining column. I have tried this with a combination of list, etc, but might be missing something that is obvious.
dt中的所有uid是唯一的。
All uids in dt are unique.
提前感谢。
推荐答案
对于data.table重塑,请尝试以下操作: p>
For a data.table reshape, try the following:
dt[, list(variable = names(.SD), value = unlist(.SD, use.names = F)), by = uid]
语法的代价是值得的;该函数运行非常快!
The cost of the syntax is worth it; the function runs very quickly!
这篇关于数据透视表类似于重塑熔化函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!