Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.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 - Fatal编程技术网

R 基于条件创建序列

R 基于条件创建序列,r,R,如果前一个值大于当前值,如何有条件地递增?假设我的数据帧上有一列x,我想要一列y,它从1开始,如果上一个值大于当前值,则递增 x y 1 1 2 1 3 1 4 1 5 1 6 1 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 1 3 2 3 5 3 正如@A5C1D2H2I1M1N2O1R2T1所提到的,您可以使用cumsum和diff来生成y cumsum(diff(x) < 0) + 1 #[

如果前一个值大于当前值,如何有条件地递增?假设我的数据帧上有一列x,我想要一列y,它从1开始,如果上一个值大于当前值,则递增

x   y
1   1
2   1
3   1
4   1
5   1
6   1
1   2
2   2
3   2
4   2
5   2
6   2
7   2
8   2
1   3
2   3
5   3

正如@A5C1D2H2I1M1N2O1R2T1所提到的,您可以使用
cumsum
diff
来生成
y

cumsum(diff(x) < 0) + 1
#[1] 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3
数据

x <- c(1:6, 1:8, 1, 2, 5)

x看看
diff
@Sathish这取决于你所说的“工作”是什么意思。它将完全适用于需要向量减少的总次数的情况。这就是OP的要求。
x <- c(1:6, 1:8, 1, 2, 5)