r - Element wise mean from data frame -


i have data frame 3 columns , 16 rows. each element has values row1 values (0.9, 0.9, 1.0), (0.7,0.9, 1.0), (0.9, 0.9, 1.0). want element wise mean e.g., (0.9+0.7+0.9/3), (0.9+0.9+0.9/3), (1.0+1.0+1.0/3) , store result new column. suggestions?

      sho1          sho2             sho3 1  0.7, 0.9, 1.0   0.9, 0.9, 1.0   0.7, 0.9, 1.0 2  0.7, 0.9, 1.0   0.9, 0.9, 1.0   0.7, 0.9, 1.0 3  0.0, 0.0, 0.1   0.9, 0.9, 1.0   0.0, 0.0, 0.1 

expected out row1:

0.7+0.9+0.7/3, 0.9+0.9+0.9/3, 1.0+1.0+1.0/3 

based on dput output op (in comments), found columns in 'df1' not 'strings'. infact each element of each column list. so, instead of doing strsplit (as suggested earlier), loop through columns lapply , rbind list elements (do.call(rbind). output 'list' contains 'matrix' list elements.
can use reduce take elementwise sum (reduce('+', ..), , divide length of list i.e. 3.

the matrix output ('m1') can pasted rowwise (do.call(paste) after converting 'data.frame' , create new column in original dataset ('df1').

m1 <- reduce('+', lapply(df1, function(x) do.call(rbind, x)))/ncol(df1) df1$newcol <- do.call(paste, c(as.data.frame(m1), sep=", ")) df1 #           sho1          sho2          sho3 #1 0.9, 0.9, 1.0 0.7, 0.9, 1.0 0.9, 0.9, 1.0 #2 0.9, 0.9, 1.0 0.7, 0.9, 1.0 0.9, 0.9, 1.0 #3 0.3, 0.5, 0.7 0.7, 0.9, 1.0 0.3, 0.5, 0.7 #4 0.7, 0.9, 1.0 0.9, 0.9, 1.0 0.9, 0.9, 1.0 #                                     newcol #1                 0.833333333333333, 0.9, 1 #2                 0.833333333333333, 0.9, 1 #3 0.433333333333333, 0.633333333333333, 0.8 #4                 0.833333333333333, 0.9, 1 

data

df1 <-  structure(list(sho1 = structure(list(vh = c(0.9, 0.9, 1),  vh = c(0.9,  0.9, 1), m = c(0.3, 0.5, 0.7), h = c(0.7, 0.9, 1)), .names = c("vh",  "vh", "m", "h")), sho2 = structure(list(h = c(0.7, 0.9, 1), h = c(0.7,  0.9, 1), h = c(0.7, 0.9, 1), vh = c(0.9, 0.9, 1)), .names = c("h",  "h", "h", "vh")), sho3 = structure(list(vh = c(0.9, 0.9, 1),  vh = c(0.9, 0.9, 1), m = c(0.3, 0.5, 0.7), vh = c(0.9, 0.9,  1)), .names = c("vh", "vh", "m", "vh"))), .names = c("sho1",  "sho2", "sho3"), row.names = c(na, 4l), class = "data.frame") 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -