【问题标题】:Check multiple columns if any of them is a particular value检查多个列,如果它们中的任何一个是特定值
【发布时间】:2022-01-09 14:14:42
【问题描述】:

我想检查多个列中的特定字符串,如果其中至少有一个匹配,则返回一个值。

例如:

df %>%
  mutate(
    result = case_when(
      col1 == "string" |
      col2 == "string" | 
      col3 == "string" | 
      col4 == "string" | 
      col5 == "string" ~ as.integer(1),
      T ~ as.integer(2)
    )
  )

有没有办法做到这一点,即在每一列中检查至少一个 NA 并将值分配给结果?

【问题讨论】:

标签: r dataframe dplyr


【解决方案1】:

您可以通过dplyr::across查看每一行

例如数据df定义如下

df <- data.frame(
  col1 = c("string","a","a","a","a", NA),
  col2 = c("b","b","string","b","b","b"),
  col3 = c("c","c","c","c","c","c"),
  col4 = c("d","d","d","d","d","d")
)
    col1   col2 col3 col4
1 string      b    c    d
2      a      b    c    d
3      a string    c    d
4      a      b    c    d
5      a      b    c    d
6   <NA>      b    c    d

你可以试试

df %>%
  rowwise %>%
  mutate(res = ifelse(rowSums(across(col1:col4, ~ .x == "string"), na.rm = T)>0, 1, 2),
         res2 = rowSums(across(col1:col4, ~ is.na(.x)))>0)

res中,如果任一列有"string",则rowSums(...)为正值,则赋值1,否则赋值2。

同样,res2 会检查是否存在NA

请注意,它们是按行操作的。

结果是这样的

  col1   col2   col3  col4    res res2 
  <chr>  <chr>  <chr> <chr> <dbl> <lgl>
1 string b      c     d         1 FALSE
2 a      b      c     d         2 FALSE
3 a      string c     d         1 FALSE
4 a      b      c     d         2 FALSE
5 a      b      c     d         2 FALSE
6 NA     b      c     d         2 TRUE 

如果有任何问题或疑问,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-17
    • 2019-06-23
    • 2020-09-16
    • 2019-05-26
    • 2012-12-04
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多