基于R中元素的索引在嵌套列表上应用拆分

时间:2017-12-10 16:44:03

标签: r nested-lists

我是R的新手,经过一些研究后,我找不到解决问题的方法。

我试图根据字符索引拆分嵌套列表(如果索引是偶数,则存储在'even'中,如果索引是奇数,则存储在'奇')。 我已经设法使用for循环解决了这个问题,但不希望继续这种方法,因为我试图解析的数据非常大。

没有嵌套列表,以下语句可以工作(因为它是一个简单的字符列表)。 我正在使用的拆分是拆分父列表的元素而不是嵌套列表。

odd <- x[(2*(1:(length(x)/2))-1)] even <- x[2*(1:(length(x)/2))]

这是我为了更好地解释问题而生成的示例的代码片段

test <- vector(mode = "list",length = 0)
new <- "a b c d e f g h i g k"
new <- strsplit(new, split = " ")
new1 <- "l m n o p q"
new1 <- strsplit(new1, split = " ")
new2 <- "q s t u v w x"
new2 <- strsplit(new2, split = " ")
new3 <- "y z"
new3 <- strsplit(new3, split = " ")
test <- c(test, new,new1,new2,new3)

odd <- test[(2*(1:(length(test)/2))-1)]
even <- test[2*(1:(length(test)/2))]

所需结果如下:

>odd
[[1]]
[1] "a" "c" "e" "g" "i" "k"
[[2]]
[1] "l" "n" "p"
[[3]]
[1] "q" "t" "v" "x"
[[4]]
[1] "y"

>even
[[1]]
[1] "b" "d" "f" "h" "j"
[[2]]
[1] "m" "o" "q"
[[3]]
[1] "s" "u" "w"
[[4]]
[1] "z"

使用上面显示的代码获得的结果:

>odd
[[1]]
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k"
[[2]]
[1] "q" "s" "t" "u" "v" "w" "x"
>even
[[1]]
[1] "l" "m" "n" "o" "p" "q"
[[2]]
[1] "y" "z"

如果有人能帮我解决问题,我会非常感激。

2 个答案:

答案 0 :(得分:2)

使用短逻辑向量循环的事实:

odd <- lapply(test, "[", c(TRUE, FALSE))
even <- lapply(test, "[", c(FALSE, TRUE))

答案 1 :(得分:1)

一个选项是split每个元素,然后使用purrr::transpose将您的列表重新排列为偶数和奇数列表:

test <- list(c("a", "b", "c", "d", "e", "f", "g", "h", "i", "g", "k"), 
             c("l", "m", "n", "o", "p", "q"),
             c("q", "s", "t", "u", "v", "w", "x"), 
             c("y", "z"))

library(purrr)

test_split <- test %>% 
    map(~split(.x, rep_along(.x, c('odd', 'even')))) %>% 
    # just `map(split, c('odd', 'even'))` will work, but warns about recycling
    transpose()

str(test_split)
#> List of 2
#>  $ even:List of 4
#>   ..$ : chr [1:5] "b" "d" "f" "h" ...
#>   ..$ : chr [1:3] "m" "o" "q"
#>   ..$ : chr [1:3] "s" "u" "w"
#>   ..$ : chr "z"
#>  $ odd :List of 4
#>   ..$ : chr [1:6] "a" "c" "e" "g" ...
#>   ..$ : chr [1:3] "l" "n" "p"
#>   ..$ : chr [1:4] "q" "t" "v" "x"
#>   ..$ : chr "y"