Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R list - combine elements with same name

Tags:

list

r

I have a list in R:

A = list(c(1,4), 2, 3, c(1,4))

names(A) <- c("name 1", "name 2", "name 2", "name 3")

$`name 1`
[1] 1 4

$`name 2`
[1] 2

$`name 2`
[1] 3

$`name 3`
[1] 1 4

I want to combine the list elements with the same name. Output would look like this

$`name 1`
[1] 1 4

$`name 2`
[1] 2 3

$`name 3`
[1] 1 4

How would I achieve this?

like image 488
user1987607 Avatar asked Jul 13 '19 15:07

user1987607


Video Answer


1 Answers

An option would be to use names as a grouping variable after unlisting the list and use it in tapply to concatenate the elements that belong to the same group

tapply(unlist(A, use.names = FALSE), rep(names(A), lengths(A)), FUN = c)
#$`name 1`
#[1] 1 4

#$`name 2`
#[1] 2 3

#$`name 3`
#[1] 1 4

Or using split

split(unlist(A, use.names = FALSE), rep(names(A), lengths(A)))

Or a compact option with stack and split

with(stack(A), split(values, ind))

Or loop through the unique names of 'A', do a == to select the elements of 'A' that belong to the same name

lapply(unique(names(A)), function(x) unlist(A[x== names(A)], use.names = FALSE))
like image 75
akrun Avatar answered Oct 12 '22 10:10

akrun