已经有很多关于reshape2
库的问题,但是我对一段可以一次重塑我需要的所有列的代码感兴趣。我有一个电话使用情况数据集,其中包含每个用户的日常电话使用情况(例如频率,持续时间),再除以不同的应用类别。前10个样本的dput:
structure(list(X = 1:10, user_id = c(10161L, 10161L, 10161L,
10161L, 10161L, 10161L, 10161L, 10161L, 10161L, 10161L), date = c("2019-02-21",
"2019-02-21", "2019-02-21", "2019-02-21", "2019-02-22", "2019-02-22",
"2019-02-22", "2019-02-22", "2019-02-22", "2019-02-23"), categories = c("communication",
"games & entertainment", "lifestyle", "utility & tools", "communication",
"games & entertainment", "lifestyle", "social network", "utility & tools",
"communication"), frequency = c(30L, 13L, 3L, 15L, 99L, 19L,
8L, 2L, 73L, 57L), cat_duration = c(1663.83800005913, 1855.2380001545,
38.9109997749329, 1016.48200011253, 7044.4249997139, 8498.35199904442,
71.5590000152588, 741.676999807358, 2657.03099822998, 5145.73099899292
), dur_pro = c(0.363722652841753, 0.40556357472605, 0.00850612383078189,
0.222207648601416, 0.370504849244312, 0.446974824255909, 0.00376367929444972,
0.0390088509726144, 0.139747796232715, 0.314487675459045), freq_pro = c(0.491803278688525,
0.213114754098361, 0.0491803278688525, 0.245901639344262, 0.492537313432836,
0.0945273631840796, 0.0398009950248756, 0.00995024875621891,
0.36318407960199, 0.463414634146341), monetary = c(55.4612666686376,
142.7106153965, 12.970333258311, 67.7654666741689, 71.1558080779182,
447.281684160233, 8.94487500190735, 370.838499903679, 36.39768490726,
90.2759824384723), recency = c(6504.5680000782, 5023.14100003242,
26999.1610000134, 32.4110000133514, 518.858000040054, 209.592000007629,
30790.6349999905, 4608.17300009727, 14603.4340000153, 68.6960000991821
)), row.names = c(NA, 10L), class = "data.frame")
通过使用reshape2
库,我可以将其转换为所需的格式,但是一次只能接受一个变量作为value.var
的参数,例如,针对频率:>
dcast(phone_usage, user_id+date~categories, value.var = 'frequency')
是否有一种方法可以一次转换所有6个功能?我相信有一种比分别转换并合并它们更简单的方法... (frequency,cat_duration,dur_pro,freq_pro,monetary,recency)
预先感谢您的贡献!
PS:我知道将数据帧转换为较宽格式时的缺失值问题,但是现在让我们忽略该问题。
答案 0 :(得分:1)
您可以使用data.table
来使用多个value.var
library(data.table)
dcast(setDT(phone_usage), user_id + date ~ categories, value.var = c(names(phone_usage[,5:10])))