如果接受另外3列的条件,则用同一列下一行的NA替换值

时间:2019-05-17 04:46:50

标签: r replace conditional

如果3列的条件与上一行相同,则我需要用NA替换同一列的下一行中的数据。如何编写这种情况的代码?

例如我有这样的示例数据

store camp  var    value
 a     1     ax     200
 b     2     bx     100
 a     1     ax     200
 b     2     bx     100
 c     2     cx     100
 a     1     ax     200
 c     2     cx     100

要这样

store camp  var    value
 a     1     ax     200
 b     2     bx     100
 a     1     ax     NA
 b     2     bx     NA
 c     2     cx     100
 a     1     ax     NA
 c     2     cx     NA

反正有这样做吗?提前谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用重复的-这与您拥有的重复

 x <- data.frame( 
 store = c( "a","b","a","b","c","a","c"),
 camp = c(1,2,1,2,2,1,2),
 var = c( "ax","bx","ax","bx","cx","ax","cx"),
 value = c( 200,100,200,100,100,200,10))

 x[ duplicated( x[ , c( "store","camp","var")]) ,"value"] <- NA