2014-01-23 77 views
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

你可以這樣做:

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僅使用替換向量的第一個值並給出警告。

+0

感謝您的解釋。這現在很有意義。 – Chad

1

使用data.table

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

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

你也可以做到這一點在base R使用withintransform

2

使用transform()ifelse()

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

這是聰明的。非常感謝 – Chad

0

另一種方法不ifelse,沒有索引:

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