Gabriel
Gabriel

Reputation: 55

Transforming dataframes by values of multiple columns

I have a dataframe that I need to transform based on values in multiple columns. The data frame is as follows:

Cond        Exp      pathoffset
-------------------------------
congruent   standard 0.06819259
congruent   standard 0.27370488
incongruent standard 0.34841871
incongruent standard 0.21540861
congruent   forced   0.19483575
congruent   forced   0.35533876
incongruent forced   0.19483575
incongruent forced   0.35533876

The dataframe I have been attempting to get is

con_stand   incon_stand   con_for   incon_for   
----------------------------------------------
0.06819259  0.34841871  0.19483575  0.19483575
0.27370488  0.21540861  0.35533876  0.35533876

Any help would be appreciated

Thanks

Upvotes: 0

Views: 47

Answers (2)

cogitovita
cogitovita

Reputation: 1745

Use the 1st and 2nd column as index to group the 3rd column, and then use sapply or do.call to unroll the list.

sapply(tapply(df[,3], paste(df[,1], df[,2], sep = "_"), c), "[")

or

do.call(cbind, tapply(df[,3], paste(df[,1], df[,2], sep = "_"), c))

Upvotes: 1

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

You can use dcast from "reshape2" after you add an "ID" variable.

mydf$id <- ave(mydf$Cond, mydf$Cond, mydf$Exp, FUN = seq_along)
library(reshape2)
dcast(mydf, id ~ Cond + Exp, value.var = "pathoffset")
#   id congruent_forced congruent_standard incongruent_forced incongruent_standard
# 1  1        0.1948358         0.06819259          0.1948358            0.3484187
# 2  2        0.3553388         0.27370488          0.3553388            0.2154086

Upvotes: 1

Related Questions