Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R基于前一行中的值构建子集_R_Row_Subset - Fatal编程技术网

R基于前一行中的值构建子集

R基于前一行中的值构建子集,r,row,subset,R,Row,Subset,我有一个问题要解决: 假设我的数据是这样的: Num condition y 1 a 1 2 a 2 3 a 3 4 b 4 5 b 5 6 b 6 7 c 7 8 c 8 9 c 9 10 b 10 11 b 11 12 b 12 我现在想对b进行计算(例如,平均值),这取决于值是在b之前的行中,在本例中是a还是c? 谢谢你的帮助!!! 安吉丽卡这就是你想要的吗 # in order to se

我有一个问题要解决: 假设我的数据是这样的:

Num condition     y
1   a   1
2   a   2
3   a   3
4   b   4
5   b   5
6   b   6
7   c   7
8   c   8
9   c   9
10  b   10
11  b   11
12  b   12
我现在想对b进行计算(例如,平均值),这取决于值是在b之前的行中,在本例中是a还是c? 谢谢你的帮助!!! 安吉丽卡这就是你想要的吗

# in order to separate between different runs of condition 'b',
# get length and value of runs of equal values of 'condition'
rl <- rle(x = df$condition)
df$run <- rep(x = seq_len(length(rl$lengths)), times = rl$lengths)

# calculate sum of y, on data grouped by condition and run, and where condition is 'b'
aggregate(y ~ condition + run, data = df, subset = condition == "b", sum)
#为了在条件“b”的不同运行之间进行分离,
#获取相等“条件”值的运行的长度和值
rl您可以使用以下命令将“滞后”条件列添加到数据帧(假设
DF


为了便于帮助您,请您添加一个预期输出的示例。“b”之前的值是否应确定是否执行了计算?还是要执行不同的计算?请更具体一点。嗨,亨里克,非常感谢你的回答!我需要对y中的值进行计算,计算所有b的前面都是a或c,因此b的和在b之前,例如(15)或b的和在c之前(33)。谢谢!!!嗨,费迪南德。卡夫,谢谢你的回答。然而,在我的数据集中,这将不起作用,因为它的眼球跟踪数据和大量NA之间存在差异。另外,在这个例子中,总是有相同数量的行,这在我的真实dataHi Henrik中不是这样的,非常感谢您的回答。它起作用了!但就我的数据而言,情况更为复杂——数据看起来有点像这样:Num Condition Gaze_time AOI_Hit 1a 20 1 2 a 20 1 3 b 10 0 4 b 30 1 7 c 10 1 8 b 50 1 9 b 50 1 10 b 10 0 11 b 60 1我现在要计算Gaze_time,这取决于AOI_Hit是0还是1——但也要根据“b”前面是否有“a”或“c”。我希望这是可以理解的…非常感谢!!!
> DF <- within(DF, lag_cond <- c(NA, head(as.character(condition), -1)))
   Num condition  y lag_cond
     1         a  1     <NA>
     2         a  2        a
     3         a  3        a
     4         b  4        a
     5         b  5        b
     6         b  6        b
     7         c  7        b
     8         c  8        c
     9         c  9        c
    10         b 10        c
    11         b 11        b
    12         b 12        b
> DF[with(DF, condition=="b" & lag_cond %in% c("a","c")),]
   Num condition  y lag_cond
     4         b  4        a
    10         b 10        c