Map_dbl function not work

Please help, I try to sum up all the content in iris,and not sum for the non numeric variable
the code as below :

iris %>% map_dbl(function(x) if(is.numeric(x)) sum(x))

why the code is not work, it is worked if I removed the non numeric variable first, as below
iris[1:4] %>% map_dbl(function(x) if(is.numeric(x)) sum(x))

A better function candidate for what you want to do is summarise_if:

iris %>% summarise_if(is.numeric, sum)

Can also be written as

iris %>% summarise(across(where(is.numeric), sum))

does this means, that map_dbl is not applicable to do this task?

Depends on intended output. The map functions always return a list or vector of the same length as input, so summarise is a better option if you want to leave one column out.

If you want to keep the Species column, just not summed, you can do iris %>% map_if(is.numeric, sum)

The output of map is a list, so if you unlist it, you get the following

unlist(iris %>% map(function(x) if(is.numeric(x)) sum(x)))
#> Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
#>        876.5        458.6        563.7        179.9

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.