0

This is more of an educaitonal question, I am trying to spin my head around map function in R (Do let me know if thats obsolete already). But what I want is sum of all numeric columns & I am trying this

iris %>% select(map(c('Sepal.Length','Sepal.Width','Petal.Length','Petal.Width')),rowSums,vars=colnames(.))

Error received is

Error in as_mapper(.f, ...) : argument ".f" is missing, with no default

I know its wrong but I want to understang basic concept/fundamental behind this rather than just getting right answer, little explanation would really help. Also, do let me know if there is a better way to do this in tidyverse itself

Vaibhav Singh
  • 1,159
  • 1
  • 10
  • 25
  • Although you can do this with `map`, but I think a more straight-forward approach is `iris %>% summarise_if(is.numeric, sum)` – Ronak Shah Dec 03 '19 at 11:14
  • I know that way & can do it, but I want to understand map function to be honest. Also, what am I doing wrong above – Vaibhav Singh Dec 03 '19 at 11:16
  • `map` is applying a function to a vector and returning a list. Within the `map` bracket you have only a vector, no function. With a function it would be iteratively doing it across the character vector supplied, what it returns doesn't make much sense to `select` either. – Andy Baxter Dec 03 '19 at 11:17

1 Answers1

2

Although a straight-forward answer to this is

library(dplyr)
library(purrr)

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

Or

cols <- c('Sepal.Length','Sepal.Width','Petal.Length','Petal.Width')
iris %>% summarise_at(cols, sum)

But if you want to do this with map, you can do

map(cols, ~iris %>% select(.x) %>% sum)

#[[1]]
#[1] 876

#[[2]]
#[1] 459

#[[3]]
#[1] 564

#[[4]]
#[1] 180

Or

map_dbl(cols, ~iris %>% select(.x) %>% sum)
#[1] 876 459 564 180

Also another variant can be

map(cols, ~iris %>% summarise_at(.x, sum))

#[[1]]
#  Sepal.Length
#1          876

#[[2]]
#  Sepal.Width
#1         459

#[[3]]
#  Petal.Length
#1          564

#[[4]]
#  Petal.Width
#1         180

There is no need for colSums here since we are summing only one column at a time, although using it would still give the answer.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    I was about to post `iris %>% select(1:4) %>% map(sum)` as another way of doing the above, but this is a much fuller explanation! – Andy Baxter Dec 03 '19 at 11:27