【发布时间】: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