【问题标题】:subtract two columns in dataframe if a condition is met如果满足条件,则减去数据框中的两列
【发布时间】:2014-01-23 22:22:44
【问题描述】:

我的数据框:

Dead4   Dead5
0       0
0       0
0       0
1       2
0       0
0       0
1       2
0       0
1       0
0       1
1       1
5      10

我希望我的代码在同一行中的任何时候说 Dead5 大于 Dead4 减去这两个值并将该值放入 Dead5

indices<- (t$Dead5 > t$Dead4) 
t$Dead6[indices]<- (t$Dead6) - (t$Dead5)


Warning message:
In t$Dead6[indices] <- (t$Dead6) - (t$Dead5) :
  number of items to replace is not a multiple of replacement length

能否解释一下我做错了什么并帮我写几行代码来解决这个问题?

【问题讨论】:

    标签: r dataframe matrix-indexing


    【解决方案1】:

    你可以这样做:

    indices <- (t$Dead5 > t$Dead4) # indices is a logical vector with TRUE and FALSE
    
    t$Dead5[indices] <- (t$Dead5 - t$Dead4)[indices]
    

    它也适用于您的 data.frame 的任何其他操作,例如:

    t$Dead6[indices] <- (t$Dead6 - t$Dead5)[indices]
    

    如果存在Dead6 列。在每一边,只取indicesTRUE 的值,因此替换值和替换值的长度相同,您不会收到警告。

    您做错了什么是您将完整的(t$Dead5 - t$Dead4) 向量作为替换,该向量比indicesTRUE 的次数长(左侧的替换值)。

    R 仅使用您的替换向量的第一个值并给您一个警告。

    【讨论】:

      【解决方案2】:

      使用transform()ifelse()

      transform(t, Dead5 = ifelse(Dead5 > Dead4, Dead5-Dead4, Dead5))
      

      【讨论】:

      • 这很聪明。非常感谢
      【解决方案3】:

      使用data.table

      library(data.table)
      DT <- as.data.table(DF)
      
      DT[Dead5 > Dead4, Dead5 := Dead5 - Dead4]
      

      您也可以在base R 中使用withintransform 执行此操作

      【讨论】:

        【解决方案4】:

        另一种不带ifelse 且不带索引的方法:

        indices <- t$Dead5 > t$Dead4 
        t$Dead6 <- t$Dead6 - (t$Dead5 * indices)
        

        【讨论】:

          猜你喜欢
          • 2018-08-29
          • 1970-01-01
          • 1970-01-01
          • 2019-09-06
          • 2020-06-27
          • 2020-09-08
          • 2023-02-24
          • 1970-01-01
          • 2022-10-13
          相关资源
          最近更新 更多