【问题标题】:pasting variables into a mutate_at function to mutate specific columns if they exist将变量粘贴到 mutate_at 函数中以改变特定列(如果存在)
【发布时间】:2019-11-19 23:15:45
【问题描述】:

我有一些数据,我正在尝试使用 mutate_at 根据它们的列名来改变一些列。 但是我不断收到以下错误:

Error: No tidyselect variables were registered

如何将一些变量粘贴到mutate_at

图书馆:

library(dplyr)
library(tidyr)

代码:

vars_to_match <- c("Petal.Length_virginica", "Sepal.Length_virginica", "Sepal.Width_setosa")

my_Data %>% 
  mutate_at(
    .var = matches(paste(vars_to_match, collapse = "|")),
    .funs = c("Scale_Me")
  )

数据:

data(iris)
my_Data <- iris %>% 
  mutate(row = row_number()) %>% 
  pivot_wider(names_from = Species, values_from = Sepal.Length:Petal.Width)

功能:

Scale_Me <- function(x){
  (x - mean(x, na.rm = TRUE)) / sd(x, na.rm = TRUE)  # Standard Normal Distribution Function
}

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    您需要使用 vars() 进行引用,而不是 .vars,即

    library(dplyr)
    
    my_Data %>%
         mutate_at(
         vars(matches(paste(vars_to_match, collapse = "|"))),
         .funs = c("Scale_Me")
       )
    

    给出,

    A tibble: 150 x 13
         row Sepal.Length_setosa Sepal.Length_versicolor Sepal.Length_virginica Sepal.Width_setosa Sepal.Width_versicolor Sepal.Width_virginica Petal.Length_setosa Petal.Length_versicolor Petal.Length_virginica Petal.Width_setosa Petal.Width_versicolor Petal.Width_virginica
       <int>               <dbl>                   <dbl>                  <dbl>              <dbl>                  <dbl>                 <dbl>               <dbl>                   <dbl>                  <dbl>              <dbl>                  <dbl>                 <dbl>
     1     1                 5.1                      NA                     NA             0.190                      NA                    NA                 1.4                      NA                     NA                0.2                     NA                    NA
     2     2                 4.9                      NA                     NA            -1.13                       NA                    NA                 1.4                      NA                     NA                0.2                     NA                    NA
     3     3                 4.7                      NA                     NA            -0.601                      NA                    NA                 1.3                      NA                     NA                0.2                     NA                    NA
    

    【讨论】:

    • 也许还推荐list(Scale_Me)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    相关资源
    最近更新 更多