【问题标题】:R: Transforming variables over many columnsR:在多列上转换变量
【发布时间】:2021-05-14 18:18:26
【问题描述】:

我想使用 across 一次转换大型 data.frame 中的多个列。

作为一个例子,我想进行这种转换

library(tidyverse)

iris %>% mutate(Sepal.Length2 = (Sepal.Length^4-min(Sepal.Length^4)) / (max(Sepal.Length^4) - min(Sepal.Length^4)))

但对于所有以“Sepal”开头的列。

我想,我可以使用这个命令,但我不知道如何添加我的功能。

iris %>% mutate(across(starts_with("Sepal")), ... )

对不起,如果它太琐碎了,但我不知道我必须进入谷歌才能找到一些有用的页面。

【问题讨论】:

    标签: r dplyr across


    【解决方案1】:

    我们可以使用

    library(dplyr)
    iris1 <- iris %>%
        mutate(across(starts_with("Sepal"),
               ~ (.^4-min(.^4)) / (max(.^4) - min(.^4)), .names = '{.col}2'))
    

    【讨论】:

    • 亲爱的朋友,OP也想改名,所以请相应地添加.namesarg。 iris %&gt;% mutate(across(starts_with('Sepal'), ~(. ^4-min(. ^4)) / (max(. ^4) - min(. ^4)),.names = '{.col}_2'))
    【解决方案2】:
    my_function <- function(x) {
      y = x^4-min(x^4)/max(x^4)/min(x^4)
      return=y
    }
    
    iris %>%
      mutate(across(starts_with("Sepal"), my_function))
    

    输出:

       Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
    1       676.5198   150.05983          1.4         0.2     setosa
    2       576.4798    80.99733          1.4         0.2     setosa
    3       487.9678   104.85493          1.3         0.2     setosa
    4       447.7453    92.34943          1.5         0.2     setosa
    5       624.9997   167.95893          1.4         0.2     setosa
    6       850.3053   231.34143          1.7         0.4     setosa
    7       447.7453   133.63093          1.4         0.3     setosa
    8       624.9997   133.63093          1.5         0.2     setosa
    9       374.8093    70.72543          1.4         0.2     setosa
    10      576.4798    92.34943          1.5         0.1     setosa
    11      850.3053   187.41343          1.5         0.2     setosa
    12      530.8413   133.63093          1.6         0.2     setosa
    13      530.8413    80.99733          1.4         0.1     setosa
    14      341.8798    80.99733          1.1         0.1     setosa
    15     1131.6493   255.99733          1.2         0.2     setosa
    .....
    

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 2018-01-03
      • 1970-01-01
      • 2022-11-24
      • 2016-03-07
      • 2018-07-23
      • 2015-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多