dataframe - Complex data frame transposition in R -


i've tried searching answer data.frame/matrix transpoitions aren't complicated trying accomplish. have data.frame looks like

          f    m    2008_b    1    5    6 2008_r    3    3    6 2008_a    4    1    5 2009_b    1    1    2 2009_r    5    4    9 2009_a    2    2    4 

i'm trying transpose , rename column , row names such:

          f_b  m_b  a_b  f_r  m_r  a_r  f_a  m_a  a_a 2008        1    5    6    3    3    6    4    1    5 2009        1    1    2    5    4    9    2    2    4 

essentially every 3 rows being collapsed in single row. assume can done clever plyr or reshape2 commands i'm @ total loss how accomplish it.

you try

library(dplyr) library(tidyr)  lvl <- c(outer(colnames(df), unique(gsub(".*_", "", rownames(df))),                         fun=paste, sep="_"))   res <- cbind(var1=row.names(df), df) %>%                               gather(var2, value, -var1) %>%                                separate(var1, c('var11', 'var12')) %>%                               unite(varn, var2, var12) %>%                               mutate(varn=factor(varn, levels=lvl)) %>%                               spread(varn, value)  row.names(res) <- res[,1] res1 <- res[,-1] res1 #     f_b m_b a_b f_r m_r a_r f_a m_a a_a #2008   1   5   6   3   3   6   4   1   5 #2009   1   1   2   5   4   9   2   2   4 

data

df <- structure(list(f = c(1l, 3l, 4l, 1l, 5l, 2l), m = c(5l, 3l, 1l,  1l, 4l, 2l), = c(6l, 6l, 5l, 2l, 9l, 4l)), .names = c("f",  "m", "a"), class = "data.frame", row.names = c("2008_b", "2008_r",  "2008_a", "2009_b", "2009_r", "2009_a")) 

Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -