【问题标题】:Looping over columns to standardize those that are numeric [duplicate]循环列以标准化数字[重复]
【发布时间】:2021-04-05 05:39:17
【问题描述】:

使用 R,我尝试遍历数据集中的所有列,并使用 for 循环、if 语句和 scale 函数标准化这些数字列。

目前我的代码如下:

for (columns in names(data)){
   if class(data[[columns]]) == "numeric"{
      data$columns = scale(data$columns)
   }
   print(columns)
}

但是,这不起作用。有什么帮助吗?

【问题讨论】:

  • 您是否需要 for 循环和 if 语句,或者您是否愿意接受其他方法,例如来自tidyverse?
  • 请同时分享您的数据示例。

标签: r loops data-manipulation


【解决方案1】:

tidyverse 方法:

library(tidyverse)
#Data
data("iris")
#Code
new <- iris %>% mutate(across(where(is.numeric),~scale(.)))

【讨论】:

    【解决方案2】:

    您可以找到数字列并将scale 应用于它。例如,使用内置的iris 数据集。

    cols <- sapply(iris, is.numeric)
    iris[cols] <- scale(iris[cols])
    iris
    
    #    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
    #1        -0.8977      1.0156      -1.3358   -1.311052     setosa
    #2        -1.1392     -0.1315      -1.3358   -1.311052     setosa
    #3        -1.3807      0.3273      -1.3924   -1.311052     setosa
    #4        -1.5015      0.0979      -1.2791   -1.311052     setosa
    #5        -1.0184      1.2450      -1.3358   -1.311052     setosa
    #6        -0.5354      1.9333      -1.1658   -1.048667     setosa
    #...
    #...
    

    【讨论】:

      猜你喜欢
      • 2020-06-30
      • 2022-01-12
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 2014-01-19
      • 2013-07-19
      • 1970-01-01
      相关资源
      最近更新 更多