【发布时间】:2018-12-22 19:39:42
【问题描述】:
我需要在下面数据集的每个行上选择一些值并计算一个总和。
这是我的数据集的一部分。
> prova
key_duration1 key_duration2 key_duration3 KeyPress1RESP KeyPress2RESP KeyPress3RESP
18 3483 364 3509 b n m
19 2367 818 3924 b n m
20 3775 1591 802 b m n
21 929 3059 744 n b n
22 3732 530 1769 b n m
23 3503 2011 2932 b n b
24 3684 1424 1688 b n m
行是实验的试验,列是按下的键,按时间顺序 (keypressRESP) 和键到下一个键的时间量 (key_duration)。
例如,在第一次试验(第一行)中,我按下“b”,3483 毫秒后按下“n”,依此类推。
这是我的数据框
structure(list(key_duration1 = c(3483L, 2367L, 3775L, 929L, 3732L,
3503L, 3684L), key_duration2 = c(364L, 818L, 1591L, 3059L, 530L,
2011L, 1424L), key_duration3 = c(3509, 3924, 802, 744, 1769,
2932, 1688), KeyPress1RESP = structure(c(2L, 2L, 2L, 4L, 2L,
2L, 2L), .Label = c("", "b", "m", "n"), class = "factor"), KeyPress2RESP = structure(c(4L,
4L, 3L, 2L, 4L, 4L, 4L), .Label = c("", "b", "m", "n"), class = "factor"),
KeyPress3RESP = structure(c(3L, 3L, 4L, 4L, 3L, 2L, 3L), .Label = c("",
"b", "m", "n"), class = "factor")), row.names = 18:24, class = "data.frame")
我需要一种在每一行(试用)中选择所有“b”值的方法,计算 sum(key_duration) 并在新列上打印这些值,“m”也是如此。
我该怎么办?
我认为我需要一个类似于 'apply()' 但不计算行上的每个值而只计算选定值的函数。
apply(prova[,1:3],1,sum)
谢谢
【问题讨论】:
-
请查看How to make a great R reproducible example,以修改您的问题,并从您的数据中提取较小的样本(check?dput())。发布您的数据或没有数据的图像会使我们难以为您提供帮助!
-
@massisenergy 感谢您的提示,对不起,我不擅长这个领域。我尝试修改问题,并添加了 dput() 输出。
-
@FilippoGambarota 您能否也显示预期的输出?你提到了
"b"和"m"- 那么"n"呢? -
@markus 我需要一个类似 apply() 的函数,但我不必对行的所有值求和,而只是对“b”值求和,并将这些值添加到新列上,“m”也是如此价值观。我不需要“n”个值。
-
您的列固定了吗?我的意思是,示例数据中是否还有这些列(例如,
key_duration4和keypress4RESP)?