identifying unique elements in sub lists and altering

后端 未结 3 1195
后悔当初
后悔当初 2021-01-21 12:32

I have the following \'list\' in R:

[[1]]
[1] 17336  5246  8597  5246 17878 19701

[[2]]
[1] 19701 37748 18155  5246  8597

[[3]]
[1] 12297 19701 17878  5246 173         


        
3条回答
  •  难免孤独
    2021-01-21 12:54

    Using @SymbolixAU's data:

    lapply(lst, function(x) tail(x, -Position(isTRUE, x==5, nomatch=-Inf)) )
    #[[1]]
    #[1] 1 2 3
    # 
    #[[2]]
    #[1] 2 3 4
    #
    #[[3]]
    #numeric(0)
    # 
    #[[4]]
    #[1] 6
    

    To explain how this works:
    1) The middle Position part just returns the negative of the index of the first time a 5 is detected, i.e.:

    sapply(lst, function(x) -Position(isTRUE, x==5, nomatch=-Inf) )
    #[1] Inf Inf  -3  -2
    

    2) tail(x, -n) just removes the first n values from a vector. When run with Inf instead, nothing is removed. Hence why Inf is used in the instance when no 5 is found.

提交回复
热议问题