I want to ask some question about pipe and nest.
df <- tibble(x = c(1, 1, 1, 2, 2, 3), y = 1:6, z = 6:1)
df_nest <- df %>% nest(data = c(y, z))
df_nest
map(.x = df_nest$data, .f = ~mean(.x$y,na.rm = TRUE)) ### how to change that with pipe
df_nest %>% map(.x = data, .f = ~mean(.x$y,na.rm =TRUE)) ### why this could not work
thank you.
I think this is a better way to work with a nested data frame
library(tidyverse)
df <- tibble(x = c(1, 1, 1, 2, 2, 3),
y = 1:6,
z = 6:1)
df %>%
nest(data = c(y, z)) %>%
mutate(mean_y = map_dbl(.x = data, .f = ~mean(.x$y, na.rm = TRUE)))
#> # A tibble: 3 × 3
#> x data mean_y
#> <dbl> <list> <dbl>
#> 1 1 <tibble [3 × 2]> 2
#> 2 2 <tibble [2 × 2]> 4.5
#> 3 3 <tibble [1 × 2]> 6
But to answer this question, you need to use a placeholder, otherwise, you would be passing the entire nested data frame as the first argument for map()
.
df %>%
nest(data = c(y, z)) %>%
map(.x = .$data, .f = ~mean(.x$y,na.rm =TRUE))
#> [[1]]
#> [1] 2
#>
#> [[2]]
#> [1] 4.5
#>
#> [[3]]
#> [1] 6
2 Likes
Thank you. I would try to understand it. Thank you!
system
Closed
August 22, 2022, 4:29pm
4
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.