【问题标题】:Replace values only in specified columns if ==0如果 ==0,则仅替换指定列中的值
【发布时间】:2019-03-16 02:21:12
【问题描述】:

我有一些看起来像这样的数据:

  ID Married Age Visits
1  1       0  35      0
2  2       1   0      7
3  3       0  29     19
df <- data.frame(
          ID = c(1L, 2L, 3L),
     Married = c(0L, 1L, 0L),
         Age = c(35L, 0L, 29L),
      Visits = c(0L, 7L, 19L)
)

想象一下,对于这个数据,Married 应该是一个虚拟变量,但AgeVisits 绝对不应该是 0。我想知道如何做两件事:

  1. 如何替换,仅在 AgeVisits 列中,将 NA 替换为 0 值?
  2. 如何替换,仅在 AgeVisits 列中,将 -999 替换为 0 值?这个只是为了好奇,因为我想知道如何在不使用na_if()的情况下做到这一点。

这段代码不太正确,因为它也改变了 Married 列。

df <- na_if(df, 0)

给予:

  ID Married Age Visits
1  1      NA  35     NA
2  2       1  NA      7
3  3      NA  29     19

而我想要的是 (1):

  ID Married Age Visits
1  1       0  35     NA
2  2       1  NA      7
3  3       0  29     19

和(2):

  ID Married Age Visits
1  1       0  35    -999
2  2       1  -999    7
3  3       0  29     19

我尝试了类似的方法:

df <- na_if(c(df$Age, df$Visits), 0))

但这是不对的。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    你可以的

    解决方案 1)

    library(dplyr)
    cols <- c("Age", "Visits")
    df[cols] <- na_if(df[cols], 0)
    
    df
    #  ID Married Age Visits
    #1  1       0  35     NA
    #2  2       1  NA      7
    #3  3       0  29     19
    

    解决方案 2)

    df[cols][df[cols] == 0] <- -999
    
    df
    #  ID Married  Age Visits
    #1  1       0   35   -999
    #2  2       1 -999      7
    #3  3       0   29     19
    

    与解决方案 2) 类似,您也可以将解决方案 1) 设为

    df[cols][df[cols] == 0] <- NA
    

    【讨论】:

      【解决方案2】:

      这是您的问题的 dplyr 解决方案。

      library(tidyverse)
      df %>% mutate_at(vars(Age,Visits),funs(na_if(.,0)))
      df %>% mutate_at(vars(Age,Visits),funs(ifelse(. == 0,-999,.)))
      

      【讨论】:

      • 出于某种原因,我在脑海中想到mutate_atfuns() 部分已被弃用为list(),但是当我尝试list() 时它不起作用。您的代码运行良好。你能解释一下funs()list()之间的区别吗?
      • 据我所知,情况并非如此。 funs() 参数指定要应用于vars() 中的变量的函数。有关详细信息,请参阅 dplyr 文档:dplyr.tidyverse.org/reference/scoped.html
      【解决方案3】:

      你可以试试

      df$Age[is.na(df$Age)] <- 0
      df$Age[df$Age == -999] <- 0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-27
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        • 2014-09-06
        • 1970-01-01
        相关资源
        最近更新 更多