【问题标题】:Unlist a column of a dataframe取消列出数据框的列
【发布时间】:2020-02-12 19:24:04
【问题描述】:

拥有这个数据框

df <- structure(list(date = c("2008-07-31", "2008-08-04"), id = c(1L, 
                                                                  1L), body = list("text 2 and here another", 
                                                                                   c("another text here", 
                                                                                     "and this in the same row", 
                                                                                     "one more in the same row"
                                                                                   ))), row.names = 1:2, class = "data.frame")

如何取消列出 body 列以获得如下输出:

 date id                                                                  body
1 2008-07-31  1                                               text 2 and here another
2 2008-08-04  1 another text here and this in the same row one more in the same row

我试过这个:

df$body <- as.data.frame(unlist(df$body))

【问题讨论】:

  • @tmfmnk 你看到了打印选项。第一个有逗号。我尝试转换的输出是 data.frame(date = c("2008-07-31", "2008-08-04"), id = c(1, 1), body = c("text 2 and here another", "another text here and this in the same row one more in the same row"))
  • 这能回答你的问题吗? How do you paste list of items in R

标签: r


【解决方案1】:

您可以在sapply 中使用paste

df$body <- sapply(df$body, paste, collapse = " ")
str(df$body)
# chr [1:2] "text 2 and here another" ...

【讨论】:

    【解决方案2】:

    使用dplyrpurrr,您可以:

    df %>%
     mutate(body = map_chr(body, paste, collapse = " "))
    
            date id                                                                body
    1 2008-07-31  1                                             text 2 and here another
    2 2008-08-04  1 another text here and this in the same row one more in the same row
    

    【讨论】:

      猜你喜欢
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 2021-04-02
      • 2016-07-08
      • 1970-01-01
      • 2021-12-22
      • 2019-05-07
      相关资源
      最近更新 更多