Reputation: 479
I have a huge dataframe with a list column(e.g)
:
join_name <- structure(list(text = list(c("The", "lady", "you", "love"),
c("The", "dog", "you", "love"))), row.names = c(NA, -2L),
class = "data.frame")
I would like to paste them together like:
join_name$text=
[1] "The lady you love"
[2] "The dog you love"
This loop do the job but is waaaay too slow :
for(i in 1:length(join_name$text)){
join_name$text[i]=paste(unlist(join_name$text[i], use.names=FALSE),collapse=" ")
}
Any idea how to do this? Thank you!
Upvotes: 1
Views: 2053
Reputation: 16842
Here's a tidyverse
way that, for a simple case, isn't really any better than base sapply
, but for more complicated workflow might have its benefits and therefore I figured it was worth adding. It replaces sapply
with purrr::map_chr
and paste
with stringr::str_c
.
library(purrr)
library(stringr)
join_name <- structure(list(text = list(c("The", "lady", "you", "love"),
c("The", "dog", "you", "love"))), row.names = c(NA, -2L),
class = "data.frame")
map_chr(join_name$text, str_c, collapse = " ")
#> [1] "The lady you love" "The dog you love"
Upvotes: 1
Reputation: 479
Thanks @MrFlick. Answer is:
join_name$text <- sapply(join_name$text, paste, collapse=" ")
Upvotes: 3