遍历向量并将该值用作数据框的列

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

我正在使用这个 for 循环来标准化我的列中的数据。这里 m_sel_cols 是一个带有列名的向量。

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

假设我的专栏名称是 "A" 那么你是:

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

我的数据集中的列数很大,我想将它转换回数据框,我知道 cbind() 可以使用,但如何在 for 循环中使用?

您可以 "loop" 使用 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

> 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 

我们可以用 tidyverse

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

数据

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