Search code examples
rdataframecbind

Iterating through a vector and using that value as column of dataframe


I am using this for loop to standardize the data in my columns. Here m_sel_cols is a vector with column names.

for(i in m_sel_cols)
    {
        cal <- work_data1$i
        cal <- ((cal-mean(cal))/sd(cal))
    }

Suppose if my column name is "A" then is you do :

  ...
        cal <- work_data1$A
  ...

The number of columns in my dataset is huge and I want to convert it back to data frame, I know cbind() can be used but how within the for loop?


Solution

  • You can "loop" through columns using sapply.

    xy <- data.frame(a = 1:3, b = 4:6, c = 7:9)
    sapply(xy, FUN = function(x) (x - mean(x))/sd(x))
    
          a  b  c
    [1,] -1 -1 -1
    [2,]  0  0  0
    [3,]  1  1  1
    

    or

    > scale(xy)
          a  b  c
    [1,] -1 -1 -1
    [2,]  0  0  0
    [3,]  1  1  1
    attr(,"scaled:center")
    a b c 
    2 5 8 
    attr(,"scaled:scale")
    a b c 
    1 1 1