有条件地将data.frame中的0值替换为NA dat

有条件地将data.frame中的0值替换为NA dat,r,R,这应该可以: dat$B[dat$B == 0 & (dat$C!=0 | dat$D!=0)] <- NA dat$C[dat$C == 0 & dat$D!=0 & is.na(dat$B)] <- NA #应用第一条规则:将0转换为NA,直到找到非负数 res1这应该有效: dat$B[dat$B == 0 & (dat$C!=0 | dat$D!=0)] <- NA dat$C[dat$C == 0 & dat$D!=0 &am

这应该可以:

dat$B[dat$B == 0 & (dat$C!=0 | dat$D!=0)] <- NA
dat$C[dat$C == 0 & dat$D!=0 & is.na(dat$B)] <- NA
#应用第一条规则:将0转换为NA,直到找到非负数
res1这应该有效:

dat$B[dat$B == 0 & (dat$C!=0 | dat$D!=0)] <- NA
dat$C[dat$C == 0 & dat$D!=0 & is.na(dat$B)] <- NA
#应用第一条规则:将0转换为NA,直到找到非负数

res1使用
data.table
-包,您可以按如下方式处理此问题:

#Apply the first rule: convert 0 to NA until we find  a non negative
res1<-t(apply(dat[,-1], 1, function(x) {
  xc <- cumsum(x) #cumulative sum
  x[xc==0]<-NA #NA where cumulative sum iz 0
  x
}))

# Apply the second rule
res2<-t(apply(res1, 1, function(x) {
  xc <- cumsum(rev(x)) #reverse the sum
  xc<-c(tail(xc,-1),1) # shift the sum
  res<-rev(x) #reverse the vector
  res[xc==0]<-NA
  rev(res)
}))

#Reconstruct the data frame
cbind(data.frame(name=dat[,1]),res2)

#   name  B  C D  E  F
#1 name1 NA NA 4  1  4
#2 name2  1  0 4  0 NA
#3 name3 NA  5 0 NA NA

同样的想法,但在R的基础上:

> dat
       A  B  C D  E  F
1: name1 NA NA 4  1  4
2: name2  1  0 4  0 NA
3: name3 NA  5 0 NA NA

新示例数据:

> dat
      A  B  C D  E  F
1 name1 NA NA 4  1  4
2 name2  1  0 0  4  0
3 name3 NA  5 0 NA NA

dat使用
data.table
-包,您可以按如下方式进行处理:

#Apply the first rule: convert 0 to NA until we find  a non negative
res1<-t(apply(dat[,-1], 1, function(x) {
  xc <- cumsum(x) #cumulative sum
  x[xc==0]<-NA #NA where cumulative sum iz 0
  x
}))

# Apply the second rule
res2<-t(apply(res1, 1, function(x) {
  xc <- cumsum(rev(x)) #reverse the sum
  xc<-c(tail(xc,-1),1) # shift the sum
  res<-rev(x) #reverse the vector
  res[xc==0]<-NA
  rev(res)
}))

#Reconstruct the data frame
cbind(data.frame(name=dat[,1]),res2)

#   name  B  C D  E  F
#1 name1 NA NA 4  1  4
#2 name2  1  0 4  0 NA
#3 name3 NA  5 0 NA NA

同样的想法,但在R的基础上:

> dat
       A  B  C D  E  F
1: name1 NA NA 4  1  4
2: name2  1  0 4  0 NA
3: name3 NA  5 0 NA NA

新示例数据:

> dat
      A  B  C D  E  F
1 name1 NA NA 4  1  4
2 name2  1  0 0  4  0
3 name3 NA  5 0 NA NA

dat@user2941942我已经更新了我的答案,以前的解决方案在正数之间有更多的零时效果不好(另请参见includen新示例数据)@user2941942我已经更新了我的答案,以前的解决方案在正数之间有更多的零时效果不好(另请参见includen新示例数据)