我有一个包含一个特定列的数据框,该列由一系列字符组成,如下所示:
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=" ")
将所有内容折叠起来。如何在列表中按向量折叠?
答案 0 :(得分:4)
可能的解决方案:
sapply(a[!!lengths(a)], toString)
或使用purrr
&#39; 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 = ',')
。