【问题标题】:Using str_subset with case_when in mutate?在变异中使用 str_subset 和 case_when?
【发布时间】:2020-06-07 16:05:30
【问题描述】:

我在 mutate 中使用 case_when 来指定特定条件时遇到了一些问题。我正在尝试创建一个名为治疗的新列,其中,如果一个国家/地区的名称(在列名称中)以元音开头,则治疗列显示为“1”。如果国家名称不以元音开头,我希望处理列显示为“0”。我在这里尝试了一些东西,但似乎没有任何效果。

mutate("treatment" = 
        case_when
        (str_subset(name, pattern = "^[AEIOU]")) ~"1", 
         str_subset(name, pattern = "[^AEIOU]") ~ "0")

当前错误消息显示:错误:列treatment 是不支持的类型引用调用。

如果有人能提供帮助,我将不胜感激!

【问题讨论】:

  • 您可以尝试从“治疗”中删除双引号吗?
  • 刚刚尝试过 - 弹出同样的错误。
  • 您能否通过分享您的数据样本来让您的问题可重现,以便其他人可以提供帮助(请不要使用str()head() 或屏幕截图)?您可以使用 reprexdatapasta 包来帮助您。另见Help me Help you & How to make a great R reproducible example?

标签: r string dplyr


【解决方案1】:

我创建了一个小示例,希望对您有所帮助。

需要考虑的一些事项:

  1. case_when() 中参数的左侧需要是逻辑语句(即TRUEFALSE 结果)。您使用的 str_subset() 函数返回与您的条件匹配的字符串,而不是逻辑字符串。在下面的示例中,我使用str_starts() 返回与您的输入条件匹配的逻辑。

  2. NULL 值在case_when() 中被忽略,但如果您愿意,也可以指定如何处理它们。查看文档?case_when 以获取相关示例。

祝你好运,欢迎来到 R!

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(stringr)

# create data frame with countries, include NA for demonstration
df <- tibble(
 country = c("Columbia", "Uruguay", "Argentina", "Brazil", NA)
)

df2 <- 
  df %>% 
  mutate(
    starts_vowel = 
      case_when(
      # left hand side of case_when must be a logical
      str_starts(country, "A|E|I|O|U") ~ 1,
      #Adding negate = TRUE returns non-matching
      str_starts(country, "A|E|I|O|U", negate = TRUE) ~ 0, 
      )
  )

df2
#> # A tibble: 5 x 2
#>   country   starts_vowel
#>   <chr>            <dbl>
#> 1 Columbia             0
#> 2 Uruguay              1
#> 3 Argentina            1
#> 4 Brazil               0
#> 5 <NA>                NA

# Check out the difference between str_subset and #str_starts
str_subset(df$country, "^[A|E|I|O|U]")
#> [1] "Uruguay"   "Argentina"
str_starts(df$country, "A|E|I|O|U")
#> [1] FALSE  TRUE  TRUE FALSE    NA

reprex package (v0.3.0) 于 2020 年 2 月 24 日创建

【讨论】:

    猜你喜欢
    • 2016-12-03
    • 2021-01-21
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 2023-02-04
    • 2022-06-15
    • 2017-09-27
    • 1970-01-01
    相关资源
    最近更新 更多