r - How to dynamically subset values and calculate the mean -


i have data frame containing 3 variables (acc , type , id), acc refers accuracy of decision, type refers 30 different decision types repeated 15 times each decision type on participants , id refers participants. looks this:

id     acc     type 1       1       1 1       0       3    1       1      10 etc... 2       1       5 2       0      13 2       0      11 etc... 

my aim analyze accuracy each decision type among participants, , merge data data frame. such as:

id    acc_type1     acc_type2 […]  acc_type30 1       70             65             87 2       65             50             90 etc... 

so far able calculate subsetting individually decision types, however, i’m looking smarter way avoid typing individually decision type value:

library(data.table) library(plyr) dt <- data.table(d,key="type") dt_type1<-data.frame (aggregate(acc~id,data=subset(dt,type==1),mean)) dt_type2<-data.frame (aggregate(acc~id,data=subset(dt,type==2),mean)) [] dt_type30<-data.frame (aggregate(acc~id,data=subset(dt,type==30),mean))  total <- merge(dt_type1,dt_type2 […] type30,by="id")  

any appreciated!

using ananda's data, data.table solution can obtained as:

require(data.table) dt <- data.table(mydf) setkey(dt, "type", "id") dt[, mean(acc), by=key(dt)][, setattr(as.list(v1), 'names',                  paste0("acc", id)), by=type] #    type acc1 acc2 acc3 # 1:    1  3.0  2.5  3.0 # 2:    2  1.5  2.0  3.0 # 3:    3  4.0  2.0  4.5 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -