6

Please help me

1) Why does map_if not work within a list
2) Is there a way to make it work
3) If not, what are the alternatives

Thanks in advance.

library(dplyr) 
library(purrr) 

cyl <- split(mtcars, mtcars$cyl) 

# This works
map_if(mtcars, is.numeric, mean) 

# This does not work 
map_if(cyl, is.numeric, mean)
J_F
  • 9,956
  • 2
  • 31
  • 55
cephalopod
  • 1,826
  • 22
  • 31

3 Answers3

6

Because you need to map to one lever lower, the columns are at level 2. So you can do:

map(cyl, ~map_if(., is.numeric, mean))

Or:

map(cyl, map_if, is.numeric, mean)

Without the if one could do

map_depth(cyl, 2, mean)
Axeman
  • 32,068
  • 8
  • 81
  • 94
3

You can try lapply:

lapply(cyl, function(x) map_if(x, is.numeric, mean))

You are attempting to use map_if() over a list of data.frames. The predicate will be tested against each data.frame, rather than each column of the data.frame e.g.

is.numeric( cyl[[1]] )
#  [1] FALSE

And that is because...

is.data.frame( cyl[[1]] )
#  [1] TRUE
Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
count
  • 1,328
  • 9
  • 16
0

map_if(cyl, is.numeric, mean) %>%as_tibble() This is pipable for plotting, summarizing, mutating, etc.

ibm
  • 744
  • 7
  • 14