r - Reshape multiple values at once -
i have long data set make wide , i'm curious if there way in 1 step using reshape2 or tidyr packages in r.
the data frame df
looks this:
id type transactions amount 20 income 20 100 20 expense 25 95 30 income 50 300 30 expense 45 250
i'd this:
id income_transactions expense_transactions income_amount expense_amount 20 20 25 100 95 30 50 45 300 250
i know can part of way there reshape2 via example:
dcast(df, id ~ type, value.var="transactions")
but there way reshape entire df in 1 shot addressing both "transactions" , "amount" variables @ once? , ideally new more appropriate column names?
in "reshape2", can use recast
(though in experience, isn't known function).
library(reshape2) recast(mydf, id ~ variable + type, id.var = c("id", "type")) # id transactions_expense transactions_income amount_expense amount_income # 1 20 25 20 95 100 # 2 30 45 50 250 300
you can use base r's reshape
:
reshape(mydf, direction = "wide", idvar = "id", timevar = "type") # id transactions.income amount.income transactions.expense amount.expense # 1 20 20 100 25 95 # 3 30 50 300 45 250
or, can melt
, dcast
, (here "data.table"):
library(data.table) library(reshape2) dcast.data.table(melt(as.data.table(mydf), id.vars = c("id", "type")), id ~ variable + type, value.var = "value") # id transactions_expense transactions_income amount_expense amount_income # 1: 20 25 20 95 100 # 2: 30 45 50 250 300
in later versions of dcast.data.table
"data.table" (1.9.8) you able directly. if understand correctly, @arun trying implement doing reshaping without first having melt
data, happens presently recast
, wrapper melt
+ dcast
sequence of operations.
and, thoroughness, here's tidyr
approach:
library(dplyr) library(tidyr) mydf %>% gather(var, val, transactions:amount) %>% unite(var2, type, var) %>% spread(var2, val) # id expense_amount expense_transactions income_amount income_transactions # 1 20 95 25 100 20 # 2 30 250 45 300 50
Comments
Post a Comment