I have a list of letters l
[1] a b c
[2] b c a b
and a vector v of letter too
[1] a
[2] b
My object is to take the letters of the vector v one by one and creating a new list that contains all the letter appearing after that letter. For example I take the first letter of v "a" and I create the list of letter appearing after "a" , And I got this :
[1] b c
[2] b
After i take the second letter or v which is "b" and I add to the list :
[3] c
[4] c a b
So the final result is :
[1] b c
[2] b
[3] c
[4] c a b
I don't know how to do this, it seems complicated.
I have also a list of vector with this format
[[1]]
[1] a
[2] b
[3] c
[[2]]
[1] e
[2] g
A nested lapply
:
lapply(v, function(v, l) lapply(l, function(x, v) {
if (!(v %in% x)) return(x) #the case of no match
x[-seq_len(which.max(x == v))]
}, v = v), l = l)
#[[1]]
#[[1]][[1]]
#[1] "b" "c"
#
#[[1]][[2]]
#[1] "b"
#
#
#[[2]]
#[[2]][[1]]
#[1] "c"
#
#[[2]][[2]]
#[1] "c" "a" "b"
Here is one approach using lapply.
dat <- list( c("a", "b", "c"), c("b", "c", "a", "b"))
v <- c("a", "b")
result <- list()
for (l in v) {
result[[l]] <- lapply(dat, function(z) z[(which(z == l)[1] + 1):length(z)])
}
result
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.