取消列出数据框的列

问题描述 投票:0回答:2

具有此数据框

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")

如何取消列出正文列以产生如下输出:

 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))
r
2个回答
1
投票

使用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

1
投票

您可以在unlist中的paste之后使用lapply

df$body <- unlist(lapply(df$body, paste, collapse = " "))
df
#        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
© www.soinside.com 2019 - 2024. All rights reserved.