您可以使用mutate
和nest()
library(tidyverse)
dfr%>%group_by(ID, price)%>%nest()%>%
mutate(location = map(data, ~select(.x, location)))%>%
select(ID, price, location)%>%ungroup()
# A tibble: 3 x 3
ID price location
<dbl> <dbl> <list>
1 1 10.2 <tibble [1 × 1]>
2 2 9 <tibble [2 × 1]>
3 3 8.5 <tibble [2 × 1]>
更新:
用这个:
dfr%>%group_by(ID, price)%>%nest()%>%
mutate(location = map(data, ~stringi::stri_paste(.x$location,collapse=',')))%>%
unnest(location)%>%
select(ID, price, location)%>%ungroup()
# A tibble: 3 x 3
ID price location
<dbl> <dbl> <chr>
1 1 10.2 A
2 2 9 B,C
3 3 8.5 F,G
一个更简单的方法是:
dfr%>%group_by(ID, price)%>%
summarise(location = stringi::stri_paste(location,collapse=','))
# A tibble: 3 x 3
# Groups: ID [3]
ID price location
<dbl> <dbl> <chr>
1 1 10.2 A
2 2 9 B,C
3 3 8.5 F,G