首页 > 解决方案 > 跨数据框中的 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))
}

标签: r

解决方案


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.namesellipse。这意味着您的 data.frame 只有一列:。c(4:14)2:12

正确的版本应该是:df <- as.data.frame(cbind(c(2:12), c(3:13), c(4:14))). 当然你应该使用函数scale而不是自己写


推荐阅读