R 发生所有预定义元素集后拆分向量

R 发生所有预定义元素集后拆分向量,r,split,R,Split,我必须做到以下几点: 我有一个向量,比如说 x您可以为此使用运行长度编码 x = c(1, 1, 2, 3, 3, 3, 4, 4, 5, 5, 3, 2, 11, 1, 3, 3, 4, 1) encoded = rle(x) # Pick the first location of 1, 2, 3, and 4 # Then find the max index location indices = c(which(encoded$values == 1)[1],

我必须做到以下几点:

我有一个向量,比如说


x您可以为此使用运行长度编码

x  = c(1, 1, 2, 3, 3, 3, 4, 4, 5, 5, 3, 2, 11, 1, 3, 3, 4, 1)
encoded = rle(x)

# Pick the first location of 1, 2, 3, and 4
# Then find the max index location
indices = c(which(encoded$values == 1)[1], 
            which(encoded$values == 2)[1],
            which(encoded$values == 3)[1],
            which(encoded$values == 4)[1])

index = max(indices)

# Find the index of x corresponding to your split location
reqd_index = cumsum(encoded$lengths)[index-1] + 2 

# Print final split value
x[reqd_index:length(x)]
结果如下

> x[reqd_index:length(x)]
 [1]  4  5  5  3  2 11  1  3  3  4  1
使用sapply查找每个预定义数字第一次出现的位置

x[-seq(max(sapply(1:4, function(y) which(x == y)[1])))]

# [1]  4  5  5  3  2 11  1  3  3  4  1
资料


它们是否需要按顺序排列-即是否应检测到1 3 2 4?如果任何答案已解决您的问题,请将其标记为已接受。阅读更多关于接受答案的详细信息。很抱歉耽搁了,我被工作或尝试做一些事情冲垮了。我已经接受了这个解决方案。。可能不需要写入编码的$values==。。。4 x。。也许像maxtaplycumsumencoded$length,encoded$values,min[c1,2,3,4]这样的东西会给你1,2,3,4条中最后一条的位置。是的,它可能被压缩成更少的代码,但我更喜欢它的可读性,除非性能受到很大影响。
x <- c(1, 1, 2, 3, 3, 3, 4, 4, 5, 5, 3, 2, 11, 1, 3, 3, 4, 1)