简体   繁体   English

将 mutate_at 与 mutate_if 一起使用

[英]Using mutate_at with mutate_if

I'm in the process of creating a generic function in my package.我正在我的包中创建一个通用函数。 The goal is to find columns that are percent columns, and then to use parse_number on them if they are character columns.目标是找到百分比列的列,然后在它们是character列时使用parse_number I haven't been able to figure out a solution using mutate_at and ifelse .我一直无法使用mutate_atifelse找出解决方案。 I've pasted a reprex below.我在下面粘贴了一个reprex。

 library(tidyverse)


df <- tibble::tribble(
  ~name, ~pass_percent, ~attendance_percent, ~grade,
  "Jon",         "90%",                0.85,    "B",
  "Jim",        "100%",                   1,    "A"
  )

percent_names <- df %>% select(ends_with("percent"))%>% names()


# Error due to attendance_percent already being in numeric value

if (percent_names %>% length() > 0) {
    df <-
      df %>%
      dplyr::mutate_at(percent_names, readr::parse_number)
  }
#> Error in parse_vector(x, col_number(), na = na, locale = locale, trim_ws = trim_ws): is.character(x) is not TRUE

your attendance_percent variable is numeric, not character and parse_number only wants character variables, see here .您的attendance_percent变量是数字,而不是字符,而parse_number只需要字符变量,请参见此处 So a solution would be:所以一个解决方案是:

edited_parse_number <- function(x, ...) {
  if (mode(x) == 'numeric') {
    x
  } else {
    parse_number(x, ...)
  }
}


df %>%
  dplyr::mutate_at(vars(percent_names), edited_parse_number)

#  name  pass_percent attendance_percent grade
#  <chr>        <dbl>              <dbl> <chr>
#1 Jon             90               0.85 B    
#2 Jim            100               1    A   

OR或者

if you didn't want to use that extra function, extract character variables at beginning:如果您不想使用该额外函数,请在开始时提取字符变量:

percent_names <- df %>% 
  select(ends_with("percent")) %>% 
  select_if(is.character) %>% 
  names()
percent_names
# [1] "pass_percent"


df %>%
  dplyr::mutate_at(vars(percent_names), parse_number)
#   name  pass_percent attendance_percent grade
#   <chr>        <dbl>              <dbl> <chr>
# 1 Jon             90               0.85 B    
# 2 Jim            100               1    A    

Alternatively, without having to create a function, you can just add an ifelse statement into mutate_at such as:或者,无需创建函数,您只需将ifelse语句添加到mutate_at例如:

if (percent_names %>% length() > 0) {
  df <-
    df %>% rowwise() %>%
    dplyr::mutate_at(vars(percent_names), ~ifelse(is.character(.), 
                                                  parse_number(.),
                                                  .))
}

Source: local data frame [2 x 4]
Groups: <by row>

# A tibble: 2 x 4
  name  pass_percent attendance_percent grade
  <chr>        <dbl>              <dbl> <chr>
1 Jon             90               0.85 B    
2 Jim            100               1    A    

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

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