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)
dput()for the input and then an explicit example of your expected dataset?yfor two different variables incolumnmean1. (2) Make your anonymous function inmapreturn something, and assign the results of the wholemap()call, not within the function, e.g.means <- map(mtcars, function(col) mean(col))(which is the same asmeans <- map(mtcars, mean)).map2orimapuntil you understandmap(andmap_dbl,map_chr, etc.)