有条件地替换特定行值

时间:2016-03-07 11:13:24

标签: r replace row conditional

我有条件替换的问题。我们假设我有一个数据帧的代码

a=c("0","1","0","B","NA","NA","NA","NA","NA")
b=c(0,1,0,0,1,0,1,0,1)
c=c(0,0,0,0,1,0,0,1,1)
d=c("0","1","0","0","1","0","B","NA","NA")
dat=data.frame(rbind(a,b,c,d))
names(dat)=c("P1","P2","P3","P4","C1","C2","C3","C4","C5")

现在我想将P1:P4的行值替换为NA,如果这些值中的一个是B,并且如果其中一个值为B,我还想用C1替换C1:C5的行值。所以我想要Dataframe看起来像这样:

a=c(**"NA","NA","NA","NA"**,"NA","NA","NA","NA","NA")
b=c(0,1,0,0,1,0,1,0,1)
c=c(0,0,0,0,1,0,0,1,1)
d=c("0","1","0","0",**"NA","NA","NA"**,"NA","NA")
dat=data.frame(rbind(a,b,c,d))
names(dat)=c("P1","P2","P3","P4","C1","C2","C3","C4","C5")

我希望这个问题是可以理解的,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

据我了解...如果在P1到P4列中找到值B,则将P1中的所有值设置为P4到NA

您可以尝试:

nm <- c("P1", "P2", "P3", "P4")
cols <- which(names(dat) %in% nm) 
dat[,cols][any(dat[,cols] == "B")] <- NA

dat
#   P1 P2 P3 P4 C1 C2 C3 C4 C5
# a NA NA NA NA NA NA NA NA NA
# b NA NA NA NA  1  0  1  0  1
# c NA NA NA NA  1  0  0  1  1 
# d NA NA NA NA  1  0  B NA NA

如果您只想将其应用于第一行,请使用dat[1,cols][any(dat[,cols] == "B")] <- NA

答案 1 :(得分:0)

考虑到dat是原始提供的数据帧,我提供了相对冗长的代码以便更好地理解。希望它有所帮助。

dat2 <- data.frame()
for(i in 1:nrow(dat)){

  datSubset <- with(dat, dat[i,])
  col.num.of.B <- which(datSubset == "B", arr.ind = T)[2]
  if(is.na(col.num.of.B)){
    datSubset <- datSubset
  } else if(col.num.of.B < 5) {
    datSubset[,c(1:4)] <- NA
  } else {
    datSubset[,c(5:9)] <- NA
  }

  dat2 <- rbind(dat2, datSubset) 
}
dat2
#    P1   P2   P3   P4   C1   C2   C3   C4   C5

# a <NA> <NA> <NA> <NA>   NA   NA   NA   NA   NA
# b    0    1    0    0    1    0    1    0    1
# c    0    0    0    0    1    0    0    1    1
# d    0    1    0    0 <NA> <NA> <NA> <NA> <NA>