-4

I am very new to R and was looking for some answers. I am trying to figure out how to calculate mean of all variables from mtcars data set,using any loop function . Any help/suggestion would be of great help

1 Answers1

2

We can use colMeans

colMeans(mtcars)

Or with tidyverse

library(dplyr)
mtcars %>%
     summarise_all(mean)

If we need a loop,

sapply(mtcars, mean)

Or using the for loop

v1 <- numeric(length(mtcars))
for(i in seq_along(mtcars)) v1[i] <- mean(mtcars[[i]])
akrun
  • 874,273
  • 37
  • 540
  • 662