【问题标题】:How can I iterate through rows and columns converting only numeric columns into z-scores? in R [duplicate]如何遍历仅将数字列转换为 z 分数的行和列?在 R [重复]
【发布时间】:2019-11-13 01:30:24
【问题描述】:

我有一个包含多种变量类型的大型数据集,但我想遍历所有数字列并将其更改为 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
    }
  }
}

【问题讨论】:

  • 也许使用scale(test[, sapply(test, is.numeric)])?如果可能只有 1 个数字列,您可能还需要 drop=FALSE

标签: r statistics economics


【解决方案1】:

您可以创建一个函数来计算z_score 并将其应用于数字列

z_score <- function(x) {(x-mean(x))/sd(x)}

cols <- sapply(test, class) == "numeric"
test[cols] <- lapply(test[cols], z_score)
test

#    pet      quant       hite       wide  color
#1   dog -0.7106195 -0.9042908 -0.7425804    red
#2   cat -0.4919673 -0.6260475 -0.5862477   blue
#3  bird -0.2733152  0.2086825 -0.1172495 purple
#4 sheep  1.4759020  1.3216559  1.4460776  white

我们也可以使用dplyr来应用这个

library(dplyr)
test %>% mutate_if(is.numeric, z_score)

正如@chinsoon12 提到的,我们可以直接使用scale

【讨论】:

    【解决方案2】:

    基础 R 解决方案:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 2021-04-11
      • 2022-01-14
      • 2022-01-02
      • 2023-02-13
      相关资源
      最近更新 更多