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?
An option would be to use names
as a grouping variable after unlist
ing 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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With