Home > Software design >  Make NA values for the specific condition in R using for sentence
Make NA values for the specific condition in R using for sentence

Time:07-11

I made a data df like this:

df <- data.frame(id = c(1,1,1,2,2,2,2,3,3),
                 year=c(2011,2012,2013,2010,2011,2012,2013,2012,2013),
                 weight=c(42,44,47,60,NA,65,66,NA,70),
                 temperature=c(NA,36,37,36,37,NA,36,36,NA))

My goal is to give two conditions to weight and make the values NA's satisfying the conditions. cond1 is the condition that weight is less than 44. The other condition cond2 is the condition that weight is bigger than 66. So if I run the code below, weight should be weight=c(NA,44,47,60,NA,65,66,NA,NA). However, the result is not I wanted.

I tried the code below:

df <- data.frame(id = c(1,1,1,2,2,2,2,3,3),
                 year=c(2011,2012,2013,2010,2011,2012,2013,2012,2013),
                 weight=c(42,44,47,60,NA,65,66,NA,70),
                 temperature=c(NA,36,37,36,37,NA,36,36,NA))
cond1<-df$weight< 44
cond2<-df$weight> 66
for(i in 1:nrow(df)){
  if(cond1){df$weight[i]=NA}
  else if(cond2){df$weight[i]=NA}
}

CodePudding user response:

You can do this without loops using ifelse and | (or):

df$weight <- ifelse(df$weight < 44 | df$weight > 66, NA, df$weight)

df$weight
[1] NA 44 47 60 NA 65 66 NA NA
  • Related