如何在 tidyr 中使用 nest() 折叠多行

how to use nest() in tidyr to collapse several rows

我有这样一个数据框

df=data.frame(a=rep(c("x","y"),2),b=c("Rome", "Venice", "Barcelona", "Paris"))

我想按 a 列嵌套 b,使其显示

x  Rome, Barcelona
y  Venice, Paris

然而这似乎并不能解决问题。有什么建议吗?

按照建议

df$b=as.character(df$b)
df=as.data.frame(df %>% group_by(a) %>% nest(b))

然而 df 的新数据列似乎是 tbl_df 格式,结果是这样的

a  data
x  list(b = c("Rome", "Barcelona")

有没有办法让新的嵌套列只是正常的字符串组合?

确保column b是一个字符:然后执行以下操作,

as.data.frame(df %>% group_by(a) %>% nest(b))
#  a            data
#1 x Rome, Barcelona
#2 y   Venice, Paris

如果column b是一个因素:那么将输出水平

> class(df$b)
[1] "factor"
> df$b
[1] Rome      Venice    Barcelona Paris    
Levels: Barcelona Paris Rome Venice

> as.data.frame(df %>% group_by(a) %>% nest(b))
#  a data
#1 x 3, 1
#2 y 4, 2

根据您要求的更改:尝试以下代码:df1 是 o/p 来自 as.data.frame()

df1 = df %>% group_by(a) %>% nest(b)    
df1$newcol = sapply(df1$data, function(x) paste(x$b, collapse = ","))
df1

       a           data         newcol
#  (fctr)          (chr)          (chr)
#1      x <tbl_df [2,1]> Rome,Barcelona
#2      y <tbl_df [2,1]>   Venice,Paris

如果您不拘泥于 tidyr / nest 解决方案,您可以 dplyr 使用:

df %>%
  group_by(a) %>%
  summarise(b = paste(b, collapse = ", "))

哪个returns:

       a               b
  <fctr>           <chr>
1      x Rome, Barcelona
2      y   Venice, Paris

如果您想使用 nest,您也可以使用 purrr 中的 map_chr 来做您想做的事:

df %>%
  mutate(b = as.character(b)) %>%
  nest(b) %>%
  mutate(cityList = map_chr(data, ~paste(.$b, collapse = ", "))) %>%
  select(-data)

请注意,正如@joel.wilson 所指出的,为此,您可能需要将城市名称显式转换为字符(如果它们是一个因素)。它returns这个:

       a        cityList
  <fctr>           <chr>
1      x Rome, Barcelona
2      y   Venice, Paris