r - Calculate means for multiple variables in with different sizes -
i have table , code @ below:
data <- data.frame(subject = c(0,0,0,1,2,2), class = c("apple","apple","apple","orange","orange","orange"), name = c(1,1,1,0,1,1), name1 = c(0,1,1,1,1,1), name2 = c(1,1,1,0,0,1))
i want find average of each variable each class , each subject, , list table. example, table have average subject first; 0 mean 8/9 , 2 mean 5/6. second work out mean class; orange mean 2/3. breakdown average name,name1 , name2.
i have tried code below, first store header list , sort subject , class lapply. isnt working.
cols = c(head(data)) data[,lapply(.sd[,cols,with=false],mean),by=class|subject]
library(reshape2) library(dplyr) data2 <- melt(data, c("subject", "class")) data.frame(summarize(group_by(data2, subject, class), avg_val = mean(value))) -> table_for_you
Comments
Post a Comment