我尝试将两个列表合并到一个输出中
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"
但是我需要像这样的输出:
[[1]] "x1abc"
[[2]] "x2dfg"
该怎么做?
答案 0 :(得分:1)
我们可以使用mapply
并并行组合ls1
和ls2
。
mapply(function(x, y) paste0(y,paste0(x, collapse = "")), ls1, ls2)
#[1] "x1abc" "x2dfg"
答案 1 :(得分:1)
ls1 <- list(c('a', 'b', 'c'), c('d', 'f', 'g'))
ls2 <- list('x1', 'x2')
代码:
ls1 <- lapply(ls1,paste0,collapse="")
paste0(ls2,ls1)
#[1] "x1abc" "x2dfg"
或很短:
paste0(ls2,lapply(ls1,paste0,collapse=""))
答案 2 :(得分:0)
这就是您需要的:
paste0(unlist(ls2),sapply(ls1,paste0,collapse=""))
[1] "x1abc" "x2dfg"