3

我的数据框:

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

有人可以解释我做错了什么并帮助我编写几行代码来做到这一点吗?

4

4 回答 4

4

你可以这样做:

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)向量作为替换,这比 is 的次数indicesTRUE(左侧的替换值)。

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

于 2014-01-23T22:31:40.873 回答
2

使用transform()ifelse()

transform(t, Dead5 = ifelse(Dead5 > Dead4, Dead5-Dead4, Dead5))
于 2014-01-23T22:28:32.760 回答
1

使用data.table

library(data.table)
DT <- as.data.table(DF)

DT[Dead5 > Dead4, Dead5 := Dead5 - Dead4]

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

于 2014-01-23T22:27:21.813 回答
0

ifelse没有和没有索引的另一种方法:

indices <- t$Dead5 > t$Dead4 
t$Dead6 <- t$Dead6 - (t$Dead5 * indices)
于 2014-01-25T18:19:13.240 回答