calcuate the mean of trials for each subject in R

*爱你&永不变心* 提交于 2019-12-02 07:06:17

If I have to guess, then you intend to get mean of n_gambles for each subject where choice==skip, then this might work:

# Data
df<- read.table(text="subj  entropy n_gambles   trial   choice
0   high    2   0   skip
0   high    2   1   skip
0   high    2   2   skip
0   high    2   3   skip
0   high    2   4   skip
0   high    2   5   skip
1   high    32  0   buy
1   high    32  1   buy
1   high    32  2   buy
1   high    32  3   buy
1   high    32  4   buy
1   high    32  5   buy",header=T)

# Get mean
aggregate(df[df$choice == "skip","n_gambles"],
          list(subj=df[df$choice == "skip","subj"]),
          mean)

# Output
#  subj x
# 1 0 2

EDIT: As I understand you want frequency of skip per subj: Try this:

# Get counts
result <- as.data.frame(table(df$subj,df$choice))
colnames(result) <- c("subj","choice","Freq")
# Subset for "skip" and divide by 6
result <- result[ result$choice == "skip",]
result$Freq <- result$Freq/6

You can use ddply from plyr package: (You mentioned that there will be six trials, so mean is computed by dividing 6 for number of observations with just choice=skip for each subject)

library(plyr)
ddply(df,.(subj),summarise,mymean=(length(which(choice=="skip")))/6)
  subj mymean
1    0      1
2    1      0

Note: df is your data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!