Igor Misechko
Igor Misechko

Reputation: 23

R lists combine

I try combine two lists in one output

ls1 <- list(c('a', 'b', 'c'), c('d', 'f', 'g'))
ls2 <- list('x1', 'x2')
paste(ls2, ls1)
[1] "x1 c(\"a\", \"b\", \"c\")" "x2 c(\"d\", \"f\", \"g\")"

lapply(1:2, function(i) { paste0(unlist(ls2), unlist(ls1[i])) })
[[1]]
[1] "x1a" "x2b" "x1c"

[[2]]
[1] "x1d" "x2f" "x1g"

sapply(1:2, function(i) { paste0(unlist(ls2), unlist(ls1[i])) })
 [,1]  [,2] 
[1,] "x1a" "x1d"
[2,] "x2b" "x2f"
[3,] "x1c" "x1g"

But I need output like:

[[1]] "x1abc"  
[[2]] "x2dfg"

How to do this?

Upvotes: 0

Views: 46

Answers (3)

Onyambu
Onyambu

Reputation: 79228

This is what you need:

paste0(unlist(ls2),sapply(ls1,paste0,collapse=""))
[1] "x1abc" "x2dfg"

Upvotes: 0

Andre Elrico
Andre Elrico

Reputation: 11480

ls1 <- list(c('a', 'b', 'c'), c('d', 'f', 'g'))
ls2 <- list('x1', 'x2')

code:

ls1 <- lapply(ls1,paste0,collapse="")

paste0(ls2,ls1)
#[1] "x1abc" "x2dfg"

or very short:

paste0(ls2,lapply(ls1,paste0,collapse=""))

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388982

We can use mapply and combine ls1 and ls2 in parallel.

mapply(function(x, y) paste0(y,paste0(x, collapse = "")), ls1, ls2)
#[1] "x1abc" "x2dfg"

Upvotes: 1

Related Questions