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)
4
  • 1
    Welcome to Stack Overflow! Can you please read and incorporate elements from How to make a great R reproducible example? Especially the aspects of using dput() for the input and then an explicit example of your expected dataset? Commented Mar 11, 2020 at 1: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. Commented Mar 11, 2020 at 1: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)). Commented Mar 11, 2020 at 2:04
  • And don't worry about map2 or imap until you understand map (and map_dbl, map_chr, etc.) Commented Mar 11, 2020 at 2:06

1 Answer 1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.