简体   繁体   English

在 R 中的列表列表中组合元素

[英]combining elements in a list of lists in R

I have a list called samples_ID with 116 vectors, each vectors has three elements like these:我有一个名为samples_ID的列表,其中包含 116 个向量,每个向量都有如下三个元素:

"11"         "GT20-16829" "S27"

I wanna keep the 116 vectors, but combine the elements to a single element like this我想保留 116 个向量,但是像这样将元素组合成一个元素

"11_GT20-16829_S27"

I tried something like this我尝试过这样的事情

samples_ID_ <- paste(samples_ID, collapse = "_")

it returns a single vector, below is just a part of it:它返回一个向量,下面只是它的一部分:

..._c(\"33\", \"GT20-16846\", \"S24\")_c(\"33\", \"GT20-18142\", \"S72\")_c(\"34\", \"GT20-16819\", \"S50\")_c...

What am I doing wrong?我究竟做错了什么? Can you help me please?你能帮我吗? Thanks谢谢

A tidyverse option.一个整洁的选择。

library(stringr)
library(purrr)

map(samples_ID, ~ str_c(., collapse = '_'))

# [[1]]
# [1] "11_GT20-16829_S27"
# 
# [[2]]
# [1] "12_GT20-16830_S28"

Data数据

samples_ID <- list(c("11", "GT20-16829", "S27"), c("12", "GT20-16830", "S28"
))

In base R , we can use sapplybase R中,我们可以使用sapply

sapply(samples_ID, paste, collapse="_")

Another base R option using paste另一个使用paste的基本 R 选项

do.call(paste, c(data.frame(t(list2DF(samples_ID))), sep = "_"))

or或者

do.call(paste, data.frame(do.call(rbind, samples_ID)), sep = "_"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM