如果满足条件,则在数据帧中减去两列

时间:2014-01-23 22:22:44

标签: r dataframe matrix-indexing

我的数据框:

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 个答案:

答案 0 :(得分: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)向量,这比indicesTRUE的次数(左边的替换值)更长)。

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

答案 1 :(得分:2)

使用transform()ifelse()

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

答案 2 :(得分:1)

使用data.table

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

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

您也可以使用base Rwithin

transform中执行此操作

答案 3 :(得分:0)

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

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