首页 > 解决方案 > 如何变异() - 警告信息

问题描述

R的新手。

我正在尝试 mutate(location2) 但它给了我警告信息:

#fix truncated values
DFnew %>%
  mutate(location2 = case_when(
    str_starts(Location, c("s", "S", "S.")) ~ "S. SJ @ Ashley Store", 
    str_starts(Location, c("p", "P")) ~ "Pleasanton @ Ranch 99",
    TRUE ~ NA_character_
  ))

Warning messages:
1: Problem with `mutate()` input `location2`.
i longer object length is not a multiple of shorter object length
i Input `location2` is `case_when(...)`. 
2: In stri_detect_regex(string, pattern, negate = negate, opts_regex = opts(pattern)) :
  longer object length is not a multiple of shorter object length

标签: r

解决方案


str_starts或任何stringr函数接受正则表达式模式。如果您传递一个向量,它将匹配第一个模式与第一个值,第二个模式与第二个值等等。

所以尝试:

library(dplyr)
library(stringr)

DFnew <- DFnew %>%
          mutate(location2 = case_when(
                str_starts(Location, "s|S|S\\.") ~ "S. SJ @ Ashley Store", 
                str_starts(Location, "p|P") ~ "Pleasanton @ Ranch 99",
                TRUE ~ NA_character_
          ))

或者您也可以使用regex()函数 withignore_case = TRUE使正则表达式不区分大小写。

DFnew <- DFnew %>%
  mutate(location2 = case_when(
    str_starts(Location, regex("S\\.?", ignore_case = TRUE)) ~ "S. SJ @ Ashley Store", 
    str_starts(Location, regex("P", ignore_case = TRUE)) ~ "Pleasanton @ Ranch 99",
    TRUE ~ NA_character_
  ))

推荐阅读