Home > other >  Using map on specific column in list?
Using map on specific column in list?

Time:02-01

I'm trying to split a dataframe in a list of dataframes and then sort each dataframe by a specific variable using map(). I thought my approach would work, but I'm obviously not correctly passing something to the function, but I'm unsure as to how to make it work. For instance, using lapply() I could do this:

library(tidyverse)
df = iris

df %>% 
group_split(Species) %>% 
{lapply(.,function(x) {x %>% arrange(desc(Sepal.Length))})}

Using map(), I've tried this approach but it's not working:

df %>% 
group_split(Species) %>%
map(.,arrange(Sepal.Length),desc)

How can I structure this so it works? I only want to apply the map() to one of the columns as in the lapply() example.

CodePudding user response:

df %>% 
  group_split(Species) %>%
  map(~arrange(.data = .x, desc(Sepal.Length)))

or

df %>% 
  group_split(Species) %>%
  map(~.x %>% arrange(desc(Sepal.Length)))
  •  Tags:  
  • Related