Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

purrr::map_if: apply a function only to specific columns

Tags:

r

purrr

Until now, when I wanted to apply a function to, say, numeric columns only, I used

library(tidyverse)

map(diamonds[map_lgl(diamonds, is.numeric)], range, na.rm = TRUE)

Now I am wondering if this is a situation where map_if() would be less clunky. What I tried is this:

map_if(diamonds, is.numeric, range, na.rm = TRUE)

But for some reason, the range is now calculated for all columns, not only numeric ones.

Am I doing something wrong or do I misunderstand the purpose of map_if()? If the latter, what is a situtation in which I would use map_if()?

like image 228
der_grund Avatar asked Nov 20 '25 19:11

der_grund


1 Answers

We can do this with summarise_if

diamonds %>% 
     summarise_if(is.numeric, funs(list(range(.)))) %>%
     unnest
# A tibble: 2 x 7
#   carat depth table price     x     y     z
#   <dbl> <dbl> <dbl> <int> <dbl> <dbl> <dbl>
# 1 0.200  43.0  43.0   326   0     0     0  
#2 5.01   79.0  95.0 18823  10.7  58.9  31.8

The map_if will apply on the function on the numeric columns and untouch the other columns so that we get the original values from those columns. The summarise_if will subset the dataset based on the condition and apply the function on those columns

like image 122
akrun Avatar answered Nov 23 '25 08:11

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!