R在进行比较ifelse时处理NA值

时间:2014-07-01 01:21:20

标签: r if-statement na

我怎么知道>和<运营商忽略NA值?下面的代码在第1行返回NA。我希望它返回0,因为该行的两个条件都失败

##sum by values
df <- data.frame(sex=c('M','F','M'),occupation=c('Student','Analyst','Analyst'),age=c(NA,6,9), marks=c(34,65,21))
df
#df$counting <- ifelse(df$age > 5 & df$age < 8, 1, 0)
df$counting <- ifelse(df$age > 5 & df$age < 8, 1, 0)+ifelse(df$marks > 60 & df$marks < 70, 1, 0)
df

2 个答案:

答案 0 :(得分:2)

请参阅以下SO帖子:How to ignore NA in ifelse statement

关于你的问题:

df$counting <- ifelse(df$age > 5 & df$age < 8 & !is.na(df$age), 1, 0) + ifelse(df$marks > 60 & df$marks < 70, 1, 0)
> df
  sex occupation age marks counting
1   M    Student  NA    34        0
2   F    Analyst   6    65        2
3   M    Analyst   9    21        0

答案 1 :(得分:0)

您也可以使用cutfindInterval

 df$counting <- colSums(rbind(cut(df$age, c(5,8), labels=F),cut(df$marks, c(60,70),    labels=F)), na.rm=T)
 df
 #  sex occupation age marks counting
 #1   M    Student  NA    34        0
 #2   F    Analyst   6    65        2
 #3   M    Analyst   9    21        0