R:重塑成长 [英] R: reshaping wide to long
问题描述
我有一个广泛的数据框,看起来像这样:
I have a wide dataframe that looks something like this:
ID Time Amount CabMean CabNum PartMean PartNum DinnMean DinNum Ex
1 1 1 27 0.654621546 8 NA 7 0.316791872 6 0
2 1 2 82 0.667461321 3 0.327594876 4 0.346798127 2 1
3 1 3 52 0.313976132 1 NA 6 0.197837257 7 0
4 1 4 99 0.798328712 9 0.913751678 4 0.191679538 9 1
我想重塑(使用reshape2包)一个长格式,采取这种形式(只是使这些数字):
I would like to reshape (using the reshape2 package) it to a long format that takes this form (just making these numbers up):
ID Time Amount Ex Type Mean Num
1 1 2 50 0 Cab 0.65654321 7
2 1 2 50 0 Part 0.65654321 1
3 1 2 50 0 Dinn 0.65654321 4
我已经尝试过这样的事情:
I have tried something like this:
reshaped <- melt(data, id.vars = c("ID", "Time", "Amount", "Ex"))
这让我有这样的东西:
ID Time Amount Ex variable value
1 1 1 10 0 CabMean 0.6565432
2 1 2 12 0 CabMean 0.6565432
所以我只有一半的地方,不能弄清楚其余的。我如何(从我目前使用的代码,或从全新的代码)提取类型(Cab,Part,Dinn)作为一个单独的列,并创建2个额外的列保持Mean和Num值?
So I'm only about half way there and can't quite figure out the rest. How do I (either from the code I'm currently using, or from completely new code) extract the type (Cab, Part, Dinn) as a separate column, and create 2 additional columns that hold Mean and Num values?
推荐答案
我们可以使用 melt
从 data.table
可以使用模式
参数的多个度量
列。我们将'data.frame'转换为'data.table'( setDT(data)
),然后将 fusion
'long'格式。
We can use melt
from data.table
which can take multiple measure
columns with the pattern
argument. We convert the 'data.frame' to 'data.table' (setDT(data)
), then melt
to 'long' format.
library(data.table)
DT <- melt(setDT(data), measure=patterns('Mean$', 'Num$'),
variable.name='Type', value.name=c('Mean', 'Num'))
DT[, Type:=c('Cab', 'Part', 'Dinn')[Type]]
这篇关于R:重塑成长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!