Search code examples
rloopssapply

How to create a loop in R to calculate a value for each column?


I wanted to calculate the standard deviation for each column in my data set below:

    a b c
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9

I tried creating a loop like this:

for (x in 1:3){
  sdcol=sd(data[,x])
}

But I get the following error:

Error in data[, x] : object of type 'closure' is not subsettable

Can you help me with such a loop?

Thanks


Solution

  • EDIT

    I suggest you try this command, which is faster than a for cycle. Be sure that your variables are all numeric. The na.rm = TRUE argument is useful if your columns contain missing values

    sapply(data, sd, na.rm = TRUE)
    

    Example

    sapply(iris[,1:4], sd, na.rm = TRUE)
    Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
       0.8280661    0.4358663    1.7652982    0.7622377