我有超过 2000 列应该进行虚拟编码的数据。但是,偶尔会有值大于 1 的情况。所以,我想一次改变所有这些列并将大于 1 的任何内容转换为 1。这是前几列数据的片段列。

我试过使用 mutate_if,我认为它仍然是我需要的最佳选择,因为我只需要 mutate 数字“代码”列。但是,我无法正确使用语法...

    # the data
    d <- tibble(
      recordID = c("ID1", "ID2", "ID1", "ID4"),
      personNumber = c("1", "1", "2", "1"),
      code_1 =  c(0, 0, 1, 1),
      code_2 = c(0, 2, 0, 0),  # this 2 should be a 1
      code_3 = c(0, 0, 1, 2),  # this 2 should be a 1
      code_4 = c(0, 1, 0, 2)   # this 2 should be a 1
    )

    # what it looks like
    d
    # A tibble: 4 x 6
      recordID personNumber code_1 code_2 code_3 code_4
      <chr>    <chr>         <dbl>  <dbl>  <dbl>  <dbl>
    1 ID1      1                 0      0      0      0
    2 ID2      1                 0      2      0      1   # this 2 should be a 1
    3 ID1      2                 1      0      1      0
    4 ID4      1                 1      0      3      2   # this 3 & 2 should be 1

这是我的尝试以及输出应该是什么样子:
    # my attempt
    d %>%
        mutate_if(is.numeric, ifelse(. >= 1, 1, 0))   # doesn't work


    # what it should look like
    d
    # A tibble: 4 x 6
      recordID personNumber code_1 code_2 code_3 code_4
      <chr>    <chr>         <dbl>  <dbl>  <dbl>  <dbl>
    1 ID1      1                 0      0      0      0
    2 ID2      1                 0      1      0      1   # 2 has been replaced
    3 ID1      2                 1      0      1      0
    4 ID4      1                 1      0      1      1   # 3 & 2 have been replaced

最佳答案

在这种情况下,不需要使用 ifelse() 。任何比较的结果都是一个 TRUE/FALSE 逻辑向量,然后可以转换为整数向量:

d %>%
 mutate_if(is.numeric, ~ +(. >= 1))

  recordID personNumber code_1 code_2 code_3 code_4
  <chr>    <chr>         <int>  <int>  <int>  <int>
1 ID1      1                 0      0      0      0
2 ID2      1                 0      1      0      1
3 ID1      2                 1      0      1      0
4 ID4      1                 1      0      1      1

或者:
d %>%
 mutate_if(is.numeric, ~ (. >= 1) * 1)

关于r - 如何在 mutate_if 中应用 ifelse 语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57466584/

10-12 16:32