Reputation: 23
I am trying to sum up all the numeric variables in iris
, and not sum the non-numeric variables.
However, this does not work:
iris %>% map_dbl(function(x) if(is.numeric(x)) sum(x))
Why doesn't this work? It works if I remove the non-numeric variables first, as below
iris[1:4] %>% map_dbl(function(x) if(is.numeric(x)) sum(x))
Could we still use map_dbl
for this case?
Upvotes: 2
Views: 408
Reputation: 389135
You can also take a look at map_if
where you can specify separate functions to be applied for TRUE
and FALSE
condition.
purrr::map_if(iris, is.numeric, sum, .else = function(x) return(NA))
#$Sepal.Length
#[1] 876.5
#$Sepal.Width
#[1] 458.6
#$Petal.Length
#[1] 563.7
#$Petal.Width
#[1] 179.9
#$Species
#[1] NA
Upvotes: 1
Reputation: 680
The following does not work because you did not specify what R should do if the variable is not a numeric variable. That is why you encountered an error.
iris %>% map_dbl(function(x) if(is.numeric(x)) sum(x))
However, if you do specify else
, it will work:
iris %>% map_dbl(function(x) if(is.numeric(x)) sum(x) else NA)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
876.5 458.6 563.7 179.9 NA
If you filter out non-numeric variable, it will work because there is no need for R to check for else
. The if
condition will always be met.
iris[1:4] %>% map_dbl(function(x) if(is.numeric(x)) sum(x))
Alternatively, you can use dplyr
:
library(dplyr)
iris %>% summarize(across(is.numeric, sum))
Sepal.Length Sepal.Width Petal.Length Petal.Width
1 876.5 458.6 563.7 179.9
Upvotes: 3