【问题标题】:Applying a function across 3 columns in a data frame only returns one column跨数据框中的 3 列应用函数仅返回一列
【发布时间】:2019-08-23 15:43:49
【问题描述】:

我正在尝试使用下面编写的函数对数据框中的所有列进行规范化。当我尝试使用下面的 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))
}

【问题讨论】:

  • 已有scale函数,可以直接使用scale(df)也可以将cbind(as.data.frame改成data.frame(
  • 您不断地重新分配相同的 output 变量。您替换每个循环中的值,而不是添加它。

标签: r


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多