0

I am trying to run this code to find the mean of each column.

df <- data.frame(
  a = rnorm(10),
  b = rnorm(10),
  c = rnorm(10),
  d = rnorm(10)
)

output <- vector("double", length = ncol(df))
for(i in seq_along(df)) {
  output[i] <- mean(df[i])   
}
output

I am getting error for not using df[[i]] though df[1] is slicing the data frame and returning the result.

Ramakrishna S
  • 395
  • 1
  • 10
  • Welcome to Stack overflow. You might want to try `colMeans(df)`. You need to specify `mean(df[,i]) ` instead of `mean(df[i]) ` – DJJ Apr 07 '20 at 11:33
  • Check the difference in output of `mean(df[1])` vs `mean(df[[1]])`. Also go through this link https://stackoverflow.com/questions/1169456/the-difference-between-bracket-and-double-bracket-for-accessing-the-el – Ronak Shah Apr 07 '20 at 11:34

0 Answers0