我有一个数据框 df,其中包含为每个受试者记录的数字列表/向量,用于测试项目的两次重复。
subj item rep vec
s1 1 1 [2,1,4,5,8,4,7]
s1 1 2 [1,1,3,4,7,5,3]
s1 2 1 [6,5,4,1,2,5,5]
s1 2 2 [4,4,4,0,1,4,3]
s2 1 1 [4,6,8,7,7,5,8]
s2 1 2 [2,5,4,5,8,1,4]
s2 2 1 [9,3,2,6,6,8,5]
s2 2 2 [7,1,2,3,2,7,3]
对于每个项目,我想找到rep 1 的平均值的50%,然后用0 替换rep 2 向量中的最低数字,直到rep2 的平均值小于或等于rep1 的平均值。例如,对于 s1 item1:
mean(c(2,1,4,5,8,4,7))*0.5 = 2.1 #rep1 scaled down
mean(c(1,1,3,4,7,5,3)) = 3.4 #rep2
mean(c(0,0,0,0,7,5,0)) = 1.7 #new rep2 such that mean(rep2) <= mean(rep1)
删除rep 2向量中的最低数字后,我想关联rep1和rep2向量并执行一些其他次要算术函数并将结果附加到另一个(长度初始化的)数据帧。现在,我使用类似于此伪代码的循环来执行此操作:
for subj in subjs:
for item in items:
while mean(rep2) > mean(rep1)*0.5:
rep2 = replace(lowest(rep2),0)
newDataFrame[i] = correl(rep1,rep2)
用循环来做这件事似乎效率很低;在 R 中,是否有更有效的方法来查找和替换列表/向量中的最低值,直到平均值小于或等于取决于该特定项目的值?将相关性和其他结果附加到其他数据帧的最佳方法是什么?
附加信息:
>dput(df)
>structure(list(subj = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L), .Label = c("s1", "s2"), class = "factor"), item = c(1L,
1L, 2L, 2L, 1L, 1L, 2L, 2L), rep = c(1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L), vec = list(c(2, 1, 4, 5, 8, 4, 7), c(1, 1, 3, 4, 7,
5, 3), c(6, 5, 4, 1, 2, 5, 5), c(4, 4, 4, 0, 1, 4, 3), c(4, 6,
8, 7, 7, 5, 8), c(2, 5, 4, 5, 8, 1, 4), c(9, 3, 2, 6, 6, 8, 5
), c(7, 1, 2, 3, 2, 7, 3))), .Names = c("subj", "item", "rep",
"vec"), row.names = c(NA, -8L), class = "data.frame")
我希望这个数据帧作为输出(具有rep1与rep2相关性以及rep1与新rep2相关性)。
subj item origCorrel newCorrel
s1 1 .80 .51
s1 2 .93 .34
s2 1 .56 .40
s2 2 .86 .79