I have a dataframe with one specific column that is made up of a list of characters as follows:
a <- list("dyspla", c("dyspla", "dyspla"), "carcin",
c("tumour", "dyspla"), character(0), character(0),
c("carcin", "dyspla"), character(0), character(0), "dyspla")
I want it to be a character vector with the character vectors in the list collapsed as follows
c("dyspla","dyspla,dyspla","carcin","tumour,dyspla","carcin,dyspla","dyspla")
paste(a,collapse=" ") collapses everything together. How to collapse by vector within the list?
A possible solution:
sapply(a[!!lengths(a)], toString)
Or with purrr's is_empty function:
sapply(a[!sapply(a, purrr::is_empty)], toString)
which both give:
[1] "dyspla" "dyspla, dyspla" "carcin" "tumour, dyspla" "carcin, dyspla" "dyspla"
Alternatively with paste:
sapply(a[!sapply(a, purrr::is_empty)], paste, collapse = ',')
In response to your comment:
If you want to keep the empty character, you can just do sapply(a, toString) or sapply(a, paste, collapse = ',').
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With