r - 如何遍历仅将数字列转换为 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
}
}
}
解决方案
基础 R 解决方案:
test[,sapply(test, is.numeric)] <- lapply(test[,sapply(test, is.numeric)], function(x){(x-mean(x))/sd(x)}
推荐阅读
- pandas-groupby - 使用 pandas groupby() 进行 Mann-Whitney U 测试
- dictionary - 如何解决致命错误:并发映射读取和映射写入
- python - 当多个线程写入 mysql 中的单个表时会发生什么?
- .net - 在 Entity Framework 6 中使用 Empty ICollection 创建投影?
- matlab - 轴重新设置父级时不显示轴工具栏
- java - 使用 DBus 方法停止 systemd 服务
- php - 从类别页面标记中删除 Woocommerce 类别类名称
- javascript - 在 HTML 中传递 Javascript 全局变量