我有一个不同值的向量,我想合并并添加两个值,如果5后跟一个3.
输入:
vector <- c(1, 2, 7, 4, 3, 8, 5, 3, 2, 6, 9, 4, 4, 5, 6, 2, 6, 5, 3)
预期产量:
1 2 7 4 3 8 8 2 6 9 4 4 5 6 2 6 8
所以正如你所看到的那样,将5个后面的两个出现在一起以显示8.我确信有一个简单的函数可以在几秒钟内完成,我只是无法找到它.
提前致谢!
vector <- c(1, 2, 7, 4, 3, 8, 5, 3, 2, 6, 9, 4, 4, 5, 6, 2, 6, 5, 3) # get indices where 5 followed by 3 fives <- head(vector, -1) == 5 & tail(vector, -1) == 3 # add three to fives vector[fives] <- vector[fives] + 3 # remove threes vector <- vector[c(TRUE, !fives)] vector # [1] 1 2 7 4 3 8 8 2 6 9 4 4 5 6 2 6 8