首页 > 解决方案 > 如何遍历仅将数字列转换为 z 分数的行和列?在 R 中

问题描述

我有一个包含多种变量类型的大型数据集,但想遍历并将所有数字列更改为 z 分数以运行标准化回归。这是我拥有的一些测试代码和数据,但效果不佳。任何见解将不胜感激!

# z = ((x_i-mean(X)) / sd(X))

pet <- c("dog", "cat", "bird", "sheep")
quant <- c(2, 3, 4, 12)
hite <- c(5, 6, 9, 13)
wide <- c(6, 7, 10, 20)
color <- c("red", "blue", "purple", "white")

test <- data.frame(pet, quant, hite, wide, color)

test_z <- test
for (col in 1:ncol(test_z)){
  if(class(names(test_z[1, col])) != "numeric") {
    next()
  } else {
    avg <- mean(test_z[,col])
    std <- sd(test_z[,col])
    for (row in 1:nrow(test_z)) {
      z_score <- (test_z[row,col] - avg) / std
      test_z[row,col] <- z_score
    }
  }
}

标签: rstatisticseconomics

解决方案


基础 R 解决方案:

test[,sapply(test, is.numeric)] <- lapply(test[,sapply(test, is.numeric)], function(x){(x-mean(x))/sd(x)}

推荐阅读