取消列出字符串并粘贴/串联到R中

时间:2018-08-20 19:17:04

标签: r

我有一个带有列表列的大型数据框join_name <- structure(list(text = list(c("The", "lady", "you", "love"), c("The", "dog", "you", "love"))), row.names = c(NA, -2L), class = "data.frame")

join_name$text=
    [1] "The lady you love"
    [2] "The dog you love"

我想将它们粘贴到一起,

for(i in 1:length(join_name$text)){
  join_name$text[i]=paste(unlist(join_name$text[i], use.names=FALSE),collapse=" ")
}

此循环可以完成任务,但是速度太慢:

append

任何想法该怎么做?谢谢!

2 个答案:

答案 0 :(得分:2)

感谢@MrFlick。答案是:

join_name$text <- sapply(join_name$text, paste, collapse=" ")

答案 1 :(得分:0)

这是一种tidyverse的方法,在一个简单的情况下,实际上并没有比基础sapply更好,但是对于更复杂的工作流程可能会有好处,因此我认为值得补充。它将sapply替换为purrr::map_chr,并将paste替换为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"