dataframe - Looking to transpose a data frame on multiple columns in R -
here sample dataframe have
mydataf.tickersymbol mydataf.yr_qtr mydataf.act_mean 1 abc 20084 bb 2 abc 20091 bb 3 abc 20092 bb 4 abc 20093 bb 5 def 20084 bb 6 def 20091 bb 7 def 20092 bb 8 def 20093 bb 9 def 20094 bb 10 gef 20092 bb 11 gef 20093 bb 12 gef 20094 m
trying output of joining on yr_qtr
each ticker , caring missing data valued. can go through , loop , create logic checks seems through data frames should able using r dataframe capabilities?
20084 20091 20092 20093 20094 abc aa bb bb bb def bb bb bb bb bm gef bb bb m
i do:
library(tidyr) df %>% spread(mydataf.yr_qtr, mydataf.act_mean)
or using reshape2
package:
library(reshape2) dcast(df, mydataf.tickersymbol ~ mydataf.yr_qtr, value.var = "mydataf.act_mean")
which gives:
mydataf.tickersymbol 20084 20091 20092 20093 20094 1 abc bb bb bb bb <na> 2 def bb bb bb bb bb 3 gef <na> <na> bb bb m
or if need "mydataf.tickersymbol" row names, use acast
give matrix output , convert data.frame as.data.frame
library(reshape)#reshape2_1.4 as.data.frame(acast(df, mydataf.tickersymbol~mydataf.yr_qtr, value.var='mydataf.act_mean', fill='')) # 20084 20091 20092 20093 20094 # abc bb bb bb bb # def bb bb bb bb bb # gef bb bb m
Comments
Post a Comment