0

Apologies if this is a dumb question- I am quite new to R and have been trying to teach myself. I've been trying to rewrite the following code using a map function instead of a for loop.

  columnmean <- function(y){
  nc <- ncol(y)
  means <- numeric(nc)
  for(i in 1:nc){
    means[i] <- mean(y[, i])
  }
  means
}

columnmean(mtcars)

My code which uses map prints out means but it also adds the column names as well. How do I utilize map properly to avoid this? Should I be using imap or map2? Thanks!

columnmean1 <- function(y){
  nc <- ncol(y)
  means <- numeric(nc)
  map(y, function (y) means <- mean(y) )
}

columnmean1(mtcars)
alistaire
  • 42,459
  • 4
  • 77
  • 117
nzhanggh
  • 121
  • 6
  • 1
    Welcome to Stack Overflow! Can you please read and incorporate elements from [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example?rq=1)? Especially the aspects of using `dput()` for the input and then an explicit example of your expected dataset? – wibeasley Mar 11 '20 at 01:46
  • Thanks for the suggestion! I don't quite understand how to use dput() but I hope that by including the mtcars dataset it makes the issues I'm seeing more readily accessible to everyone. – nzhanggh Mar 11 '20 at 01:59
  • A couple things: (1) Careful about variable reuse in nested functions. You use `y` for two different variables in `columnmean1`. (2) Make your anonymous function in `map` return something, and assign the results of the whole `map()` call, not within the function, e.g. `means <- map(mtcars, function(col) mean(col))` (which is the same as `means <- map(mtcars, mean)`). – alistaire Mar 11 '20 at 02:04
  • And don't worry about `map2` or `imap` until you understand `map` (and `map_dbl`, `map_chr`, etc.) – alistaire Mar 11 '20 at 02:06

1 Answers1

1

You can use map_dbl :

columnmean_map <- function(y){
   purrr::map_dbl(y, mean)
}

You can also use summarise_all

columnmean_summarise <- function(y){
   dplyr::summarise_all(y, mean)
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213