Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

r - Combining lists, possibly with mapply

I have a list of lists - a simple example is given below:

my_list <- vector(mode = "list", length = 4)
my_list[[1]] <- c(1, 2, 3)
my_list[[2]] <- c(1, 2, 6)
my_list[[3]] <- c("A")
my_list[[4]] <- c("A", "B")

I would like to combine a subset of these lists based on their indices in a vector. For example if my_indices <- c(1,2,3), I would like to combine the first three lists and eliminates duplicates to get

c(1, 2, 3, 6, "A")

I can do this manually as follows:

c(my_list[[1]], my_list[[2]], my_list[[3]]) %>% 
      unique()
[1] "1" "2" "3" "6" "A"

but when i try and simplify / generalize this to

my_indices <- c(1, 2, 3)
c(my_list[[my_indices ]]) %>% 
  unique()

I get an error message:

error in my_list[[my_indices]] : recursive indexing failed at level 2

How can i combine lists in this setting. I do want a general solution, as my list of lists is large, and I want to be able to extract any subset of it. I have seen posts that use mapply in a related setting, but have not successfully got it to work.

Many thanks in advance for your help

Thomas Philips


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a tidyverse solution using reduce.

library(tidyverse)

my_list <- vector(mode = "list", length = 4)
my_list[[1]] <- c(1, 2, 3)
my_list[[2]] <- c(1, 2, 6)
my_list[[3]] <- c("A")
my_list[[4]] <- c("A", "B")

to_merge <- c(1,2,3)
unique(reduce(my_list[to_merge], c))
#> [1] "1" "2" "3" "6" "A"

Created on 2021-01-08 by the reprex package (v0.3.0)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...