Vatsal Aggarwal
Vatsal Aggarwal

Reputation: 338

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?

Upvotes: 0

Views: 64

Answers (2)

akrun
akrun

Reputation: 887158

We can do this with tidyverse

library(tidyverse)
xy %>%
     mutate_all(scale)
#   a  b  c
#1 -1 -1 -1
#2  0  0  0
#3  1  1  1

data

xy <- data.frame(a = 1:3, b = 4:6, c = 7:9)

Upvotes: 0

Roman Luštrik
Roman Luštrik

Reputation: 70643

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 

Upvotes: 3

Related Questions