As part of a dplyr/tidyr wrangling pipe, I arrived at a tibble that looks like that:
trb <-
tibble::tribble(~person, ~data_name, ~data_obj, ~some_string,
"chris", "df_mtcars", mtcars, "abc",
"rachel", "df_trees", trees, "efg",
"john", "df_iris", iris, "hij",
"nicole", "df_plantgrowth", PlantGrowth, "klm",
"ron", "df_women", women, "nop", # | notice that both ron's rows have same values
"ron", "df_cars", cars, "nop", # | except for data_name and data_obj
"jillian", "df_sleep", sleep, "tuv")
This table describes 6 people and the data object each person prefers. Annoyingly, "ron" gave 2 data preferences, so I need to somehow collapse ron's info into one row of trb.
My "collapsing strategy" is to combine both ron's data preferences inside a named list such that the final output will be
trb_output <-
tribble(~person, ~.dat, ~some_string,
"chris", mtcars, "abc",
"rachel", trees, "efg",
"john", iris, "hij",
"nicole", PlantGrowth, "klm",
"ron", list("df_women" = women,
"df_cars" = cars), "nop",
"jillian", sleep, "tuv")
One critical note is that I must get this done on the pipe. That is:
# demo to desired solution
trb_output <-
trb %>%
wrangle_this(...) %>%
wrangle_that(...)
trb_output
## # A tibble: 6 x 3
## person .dat some_string
## <chr> <list> <chr>
## 1 chris <df [32 x 11]> abc
## 2 rachel <df [31 x 3]> efg
## 3 john <df [150 x 5]> hij
## 4 nicole <df [30 x 2]> klm
## 5 ron <named list [2]> nop
## 6 jillian <df [20 x 3]> tuv
Is this possible to do using just piping?
CodePudding user response:
Do either of these work for you?
trb2 = trb %>%
nest_by(
person, some_string
)
trb3 <- trb %>%
group_by(
person, some_string
) %>%
summarise(
dta = list(data_name = data_obj)
)
Edit, this one?
trb4 <- trb %>%
group_by(
person, some_string
) %>%
summarise(
dta = ifelse(length(data_obj) > 1, list(as.list(setNames(data_obj,data_name ))), data_obj))
)
CodePudding user response:
This may not be perfect, but this seems to work:
trb %>%
group_by(across(c(-data_obj, -data_name))) %>%
summarise(data_obj = ifelse(length(data_obj) > 1, lst(setNames(data_obj,data_name)), data_obj))
person some_string data_obj
<chr> <chr> <list>
1 chris abc <df [32 x 11]>
2 jillian tuv <df [20 x 3]>
3 john hij <df [150 x 5]>
4 nicole klm <df [30 x 2]>
5 rachel efg <df [31 x 3]>
6 ron nop <named list [2]>
