我有一个带有特定列的数据框,该列由字符列表组成,如下所示:
a <- list("dyspla", c("dyspla", "dyspla"), "carcin",
c("tumour", "dyspla"), character(0), character(0),
c("carcin", "dyspla"), character(0), character(0), "dyspla")
我希望它是一个字符向量,列表中的字符向量如下折叠
c("dyspla","dyspla,dyspla","carcin","tumour,dyspla","carcin,dyspla","dyspla")
paste(a,collapse=" ")
将所有内容折叠在一起。如何在列表中按向量折叠? 最佳答案
可能的解决方案:
sapply(a[!!lengths(a)], toString)
或使用
purrr
的is_empty
函数:sapply(a[!sapply(a, purrr::is_empty)], toString)
两者都给:
[1] "dyspla" "dyspla, dyspla" "carcin" "tumour, dyspla" "carcin, dyspla" "dyspla"
或者使用
paste
:sapply(a[!sapply(a, purrr::is_empty)], paste, collapse = ',')
针对您的评论:
如果要保留空字符,可以执行
sapply(a, toString)
或sapply(a, paste, collapse = ',')
。