【问题标题】:calculate the mean of trials for each subject in R计算 R 中每个受试者的试验平均值
【发布时间】:2013-08-30 12:29:32
【问题描述】:

我这里有一个数据框:每个受试者进行 6 次试验,有 105 个受试者。

我想为每个主题找到 6 次试验的“跳过”平均值。

我该如何开始?

>     subj entropy n_gambles trial choice
1      0    high         2     0   skip
2      0    high         2     1   skip
3      0    high         2     2   skip
4      0    high         2     3   skip
5      0    high         2     4   skip
6      0    high         2     5   skip
7      1    high        32     0    buy
8      1    high        32     1    buy
9      1    high        32     2    buy
10     1    high        32     3    buy
11     1    high        32     4    buy
12     1    high        32     5    buy

【问题讨论】:

  • 你所说的“跳过”是什么意思?
  • 您真的想要 6 次(恰好是每个受试者的试验次数),还是想要给定受试者的所有试验?
  • 嗨 Roland,我的意思是每个主题 6 次试验的平均跳过次数。例如,对于 subj 0,6 次试验的“skip”平均数为 6/6 = 1。但还有其他情况混合了购买和跳过。 :)
  • 嗨,Carl,好吧,所有 105 个主题都在每种条件下进行 6 次试验,因此 6 次试验对于给定主题的所有试验都是必不可少的。

标签: r mean


【解决方案1】:

您可以使用 plyr 包中的ddply:(您提到将进行六次试验,因此平均值是通过将观察数除以 6 来计算的,每个受试者只需选择=跳过)

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

注意:df 是你的数据

【讨论】:

  • 这正是我想要的。非常感谢!!
【解决方案2】:

如果我不得不猜测,那么您打算为 choice==skip 所在的每个主题计算 n_gambles 的平均值,那么这可能会起作用:

# 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

编辑: 据我了解,您希望每个subj 的频率为skip: 试试这个:

# 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

【讨论】:

  • 我认为答案很接近,但结果“x”是赌博次数,而不是每个主题的所有试验的平均跳过次数。你能解释一下这部分代码吗?我不太明白这意味着什么? subj=df[df$cho​​ice == "skip","subj"])
  • 是的,这段代码给出了正确的平均跳过次数。非常感谢。
  • @user2707619 如果有帮助,请考虑接受作为答案和/或投票。
猜你喜欢
  • 2014-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-05
  • 2014-01-24
  • 2021-12-08
  • 1970-01-01
相关资源
最近更新 更多