senera
senera

Reputation: 85

reshape long dataframe to wide for multiple columns

There are a lot of questions about reshape2 library already, but I am interested in a piece of code that can reshape all the columns I need at once. I have a phone usage dataset containing each user's daily phone usage like frequency, duration, divided by different app categories. dput for top 10 samples:

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")

By using reshape2 library I am able to cast it into a format I need, but it only accepts one variable at a time as the argument of value.var, for instance, for frequency:

dcast(phone_usage, user_id+date~categories, value.var = 'frequency')

Is there a way to cast the 6 features all at once? I believe there is an easier way than separately cast them and combine them...(frequency,cat_duration,dur_pro,freq_pro,monetary,recency)

Thank you in advance for your contribution!

PS: I am aware of the missing value problem when the dataframe is cast into a wide format, but let's ignore that problem for now.

Upvotes: 1

Views: 53

Answers (1)

Matt
Matt

Reputation: 2987

You can use data.table to use multiple value.var

library(data.table)

dcast(setDT(phone_usage), user_id + date ~ categories, value.var = c(names(phone_usage[,5:10])))

Upvotes: 1

Related Questions