r - Combining variables in a data frame based on factor levels from another data frame -


i have dataframe:

head(diets)   sp1  sp2  sp3  sp4  sp5 1 0.4  0.4  0.1  0.2  0.0 2 1.4  0.1  0.1  0.3  3.4 3 0.5  0.6  0.1  0.4  0.0 .... 

i create new dataframe sums these values based on membership in groups (factor) dataframe:

head(groups)         spname    groupname 1   sp1       grp1 2   sp2       grp1 3   sp3       grp2 4   sp4       grp3 5   sp5       grp3 .... 

to this:

   grp1 grp2 grp3 1  0.8  0.1  0.2 2  1.5  0.1  3.7 3  1.1  0.1  0.4 

you using base r's aggregate function

step1 put both data.frames

data = data.frame(cbind(df1, t(df2))) 

step2 perform summation of values corresponding each group

out = aggregate(cbind(x1, x2,  x3) ~ v3 , data, sum) 

step3 put output desired transposing , setting column names using setnames

setnames(data.frame(t(out[,-1]),row.names = null), out[,1])  #  grp1 grp2 grp3 #1  0.8  0.1  0.2 #2  1.5  0.1  3.7 #3  1.1  0.1  0.4 

data

df1 = structure(list(v1 = 1:5, v2 = structure(1:5, .label = c("sp1",  "sp2", "sp3", "sp4", "sp5"), class = "factor"), v3 = structure(c(1l,  1l, 2l, 3l, 3l), .label = c("grp1", "grp2", "grp3"), class = "factor")), .names = c("v1",  "v2", "v3"), class = "data.frame", row.names = c(na, -5l))  df2 = structure(list(sp1 = c(0.4, 1.4, 0.5), sp2 = c(0.4, 0.1, 0.6),      sp3 = c(0.1, 0.1, 0.1), sp4 = c(0.2, 0.3, 0.4), sp5 = c(0,      3.4, 0)), .names = c("sp1", "sp2", "sp3", "sp4", "sp5"), class = "data.frame", row.names = c("1",  "2", "3")) 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -