简体   繁体   English

在数据框中的3列上应用函数只会返回一列

[英]Applying a function across 3 columns in a data frame only returns one column

I am trying to normalize all columns within a data frame using the function written below. 我正在尝试使用下面编写的函数对数据框中的所有列进行规范化。 When I try to apply it to all columns using the for loop below, the output returns only one column when I would expect three. 当我尝试使用下面的for循环将其应用于所有列时,当我期望三列时,输出仅返回一列。 The output is normalized correctly suggesting the function works and the for loop is the issue. 输出正确归一化,表明函数可以正常工作,并且for循环是问题。

seq_along(df) returns the same output 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))
}

The syntax of as.data.frame is as.data.frame(x, row.names = NULL, optional = FALSE, ...) . as.data.frame的语法是as.data.frame(x, row.names = NULL, optional = FALSE, ...) That means that in the call as.data.frame(c(2:12), c(3:13), c(4:14)) c(3:13) is being assigned to the argument row.names and c(4:14) to the ellipse . 这意味着在调用as.data.frame(c(2:12), c(3:13), c(4:14)) c(3:13)被分配给参数row.namesc(4:14)椭圆 This means that your data.frame only has one column: 2:12 . 这意味着您的data.frame只有一列:2: 2:12

The correct version should be: df <- as.data.frame(cbind(c(2:12), c(3:13), c(4:14))) . 正确的版本应为: df <- as.data.frame(cbind(c(2:12), c(3:13), c(4:14))) Of course you should use the function scale instead of writing it yourself 当然,您应该使用函数scale而不是自己编写

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM