Collapse data frame into single row and creating new columns based on row R

I have a data frame with object names and a list of statistical moments for that object, like this:

Object   Mean   IQR   Skew  
   x        1     1      1
   y        2     2      2  
   z        3     3      3

What i want is to for each row create columns with the statistical moments and the object name prefixed. Like so:

xMean xIQR xSkew yMean yIQR ySkew zMean zIQR zSkew 1 1 1 2 2 2 3 3 3

In essence what I need is to collapse a data frame to a single row such that it list all statistical moments on a single line as i'll have many rows like the final one but a finite set of columns.

Upvotes: 3

Views: 2147

Answers (2)

akrun
akrun

Reputation: 887153

You could do:

 df1$id <- 1
 reshape(df1, idvar="id", timevar="Object", direction="wide")[-1]
  #  Mean.x IQR.x Skew.x Mean.y IQR.y Skew.y Mean.z IQR.z Skew.z
  #1      1     1      1      2     2      2      3     3      3

Or using dcast, melt from reshape2

 library(reshape2)
 dcast(melt(df1, id.var=c('id', 'Object')), id~..., value.var='value')[-1]
 #   x_Mean x_IQR x_Skew y_Mean y_IQR y_Skew z_Mean z_IQR z_Skew
 #1      1     1      1      2     2      2      3     3      3

Or using dplyr and tidyr

 library(dplyr)
 library(tidyr)

  df1 %>% 
      gather(Var, Val, Mean:Skew) %>% 
      unite(VarNew,Object, Var, sep="") %>%
      spread(VarNew, Val) %>%
      select(-id)
  #    xIQR xMean xSkew yIQR yMean ySkew zIQR zMean zSkew
  #1    1     1     1    2     2     2    3     3     3

data

df1 <- structure(list(Object = c("x", "y", "z"), Mean = 1:3, IQR = 1:3, 
 Skew = 1:3), .Names = c("Object", "Mean", "IQR", "Skew"), class = "data.frame", row.names = c(NA, 
-3L))

Upvotes: 3

David Arenburg
David Arenburg

Reputation: 92292

Or maybe something like

setNames(unlist(data.frame(t(df[-1]))), paste0(rep(df[, 1], each = nrow(df)), names(df[, -1])))
# xMean  xIQR xSkew yMean  yIQR ySkew zMean  zIQR zSkew 
#     1     1     1     2     2     2     3     3     3 

Upvotes: 1

Related Questions