【问题标题】:Replace row values if sum is equal to zero in R如果 R 中的总和为零,则替换行值
【发布时间】:2017-07-27 04:35:36
【问题描述】:

如果列的总和等于 0,我想用 NA 替换列的值。想象以下列:

a b 
0 0
1 5
2 8
3 7
0 0
5 8 

我想将这些替换为:

a b 
NA NA
1 5
2 8
3 7
NA NA
5 8 

我一直在很多页面上寻找答案,但没有找到任何解决方案。

这是我迄今为止尝试过的:

df[ , 31:36][df[,31:36] == 0 ] <- NA    #With df being my dataframe and 31:36 the columns I want to apply the replacement too. 

这会将所有等于 0 的值替换为 NA

我也尝试过使用rowSums() 的其他替代方案,但没有找到解决方案。

任何帮助将不胜感激。

谢谢

【问题讨论】:

    标签: r if-statement replace dplyr


    【解决方案1】:

    这个怎么样?

    a <- df[31:36,1]
    b <- df[31:36,2]
    c <- a
    a[a+b==0] <- NA
    b[c+b==0] <- NA
    df[31:36,1] <- a
    df[31:36,2] <- b
    

    我们必须创建一个名为c 的临时变量,否则当您检查第二列时,您将添加等于NA 而不是0NA+0

    【讨论】:

      【解决方案2】:

      使用dplyr 的惯用方式是:

      library(dplyr)
      
      tb <- tibble(
        a = c(0, 1:3, 0, 5), 
        b = c(0, 5, 8, 7, 0, 8)
      )
      
      tb <- tb %>%
        # creates a "rowsum" column storing the sum of columns 1:2 
        mutate(rowsum = rowSums(.[1:2])) %>% 
        # applies, to columns 1:2, a function that puts NA when the sum of the rows is 0
        mutate_at(1:2, funs(ifelse(rowsum == 0, NA, .))) %>%
        # removes rowsum
        select(-rowsum)
      

      当然,在将代码应用于实际表格时,您可以将 1:2 替换为 31:36。

      【讨论】:

      • 完美!抱歉回复晚了。这对我帮助很大!必须熟悉使用 mutate。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多