r - rotating variable in ddply -
r - rotating variable in ddply -
i trying means column in info frame based on unique value. trying mean of column b , column c in exampled based on unique values in column a. thought .(a) create calculate unique value in (it gives unique values of a) gives mean whole column b or c.
df2<-data.frame(a=seq(1:5),b=c(1:10), c=c(11:20)) simvars <- c("b", "c") ( var in simvars ){ print(var) dat = ddply(df2, .(a), summarize, mean_val = mean(df2[[var]])) ## script assign(var, dat) } c mean_val 1 15.5 2 15.5 3 15.5 4 15.5 5 15.5
how can have take average column based on unique value column a?
thanks
you don't need loop. calculate means of b
, c
within single phone call ddply
, means calculated separately each value of a
. and, @gregor said, don't need re-specify info frame name within mean()
:
ddply(df2, .(a), summarise, mean_b=mean(b), mean_c=mean(c)) mean_b mean_c 1 1 3.5 13.5 2 2 4.5 14.5 3 3 5.5 15.5 4 4 6.5 16.5 5 5 7.5 17.5
update: separate info frames each column of means:
# add together few additional columns info frame df2 = data.frame(a=seq(1:5),b=c(1:10), c=c(11:20), d=c(21:30), e=c(31:40)) # new info frame means each level of column library(dplyr) dfmeans = df2 %>% group_by(a) %>% summarise_each(funs(mean)) # separate each column of means separate info frame , store in list: means.list = lapply(names(dfmeans)[-1], function(x) { cbind(dfmeans[,"a"], dfmeans[,x]) }) means.list [[1]] b 1 1 3.5 2 2 4.5 3 3 5.5 4 4 6.5 5 5 7.5 [[2]] c 1 1 13.5 2 2 14.5 3 3 15.5 4 4 16.5 5 5 17.5 [[3]] d 1 1 23.5 2 2 24.5 3 3 25.5 4 4 26.5 5 5 27.5 [[4]] e 1 1 33.5 2 2 34.5 3 3 35.5 4 4 36.5 5 5 37.5
r variables data.frame plyr
Comments
Post a Comment