r - 跨数据框中的 3 列应用函数仅返回一列
问题描述
我正在尝试使用下面编写的函数对数据框中的所有列进行规范化。当我尝试使用下面的 for 循环将其应用于所有列时,输出仅返回一列,而我期望为三列。输出已正确标准化,表明该函数有效,而 for 循环是问题所在。
seq_along(df) 返回相同的输出
### example df
df <- cbind(as.data.frame(c(2:12), c(3:13), c(4:14)))
### normalization function
rescale <- function(x) {
(x - min(x, na.rm = TRUE)) / (max(x, na.rm = TRUE) - min(x, na.rm = TRUE))
}
### for loop that returns one column although properly normalized
for (i in 1:ncol(df)){
i <- df[[i]]
output <- as.data.frame(rescale(i))
}
解决方案
as.data.frame 的语法是as.data.frame(x, row.names = NULL, optional = FALSE, ...)
. 这意味着在调用as.data.frame(c(2:12), c(3:13), c(4:14))
c(3:13)
中被分配给参数row.names和ellipse。这意味着您的 data.frame 只有一列:。c(4:14)
2:12
正确的版本应该是:df <- as.data.frame(cbind(c(2:12), c(3:13), c(4:14)))
. 当然你应该使用函数scale
而不是自己写
推荐阅读
- amazon-web-services - AWS 应用程序负载均衡器公共 URL 不起作用
- typescript - 将装饰器应用于模块中的每个函数的函数类型
- c# - 会话过期时,Kendo 网格不会重定向到登录页面
- r - 如何使用 tidyverse 包来获取列中出现的唯一值的运行总数?
- javascript - 在 react js 的单选组件中,当我单击一个单选按钮时,它正在选择表单中的其他单选按钮,但它传递了正确的值
- node.js - 我正在将生成的 pdf 作为 base64 pdf 字符串从服务器发送到客户端。我正在尝试使用 printJS 在客户端打印它
- php - 如何将查询字符串中的变量添加到 URL 的路径?
- ios - Swift & Firebase - 登录后更新 ViewController
- c - 读取和保存已知行数的未知长度的字符串
- npm - 安装根包会自动安装作用域库吗?