[英]Create a list from another list with R
I have a list of letters l 我有一个字母清单l
[1] a b c
[2] b c a b
and a vector v of letter too 还有字母的向量v
[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. 我的目的是一个接一个地向量v的字母,并创建一个新列表,其中包含该字母之后出现的所有字母。 For example I take the first letter of v "a" and I create the list of letter appearing after "a" , And I got this :
例如,我取v的第一个字母“ a”,然后创建出现在“ a”之后的字母列表,得到的是:
[1] b c
[2] b
After i take the second letter or v which is "b" and I add to the list : 在我拿第二个字母或v(即“ b”)并将其添加到列表后:
[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
:
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. 这是使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.