根据R中的条件从列中删除NA

时间:2015-12-17 16:42:42

标签: r if-statement na

我有一个数据框,根据两列的条件,我想从不同的列中删除NA的行。

我试过了,但它似乎没有起作用:

removerows<-ifelse(df$MONTH==12 & 
df$YEAR==2015,
df[complete.cases(df$Retlisher),],
df[!complete.cases(df$Retlisher),])

当我尝试这个时,R崩溃了。这是原始数据框:

  Place1234   We_source Wevisetiser   MONTH YEAR Weater.Size Revenue QP.TERuests Opportunities PaTP.WQpreOPIons
1                             <NA> MTD: 12 2015       LARGE       0      219768             0                0
2            abcdefghij abcdefghij      12 2015     UNKNOWN       0           0             2                0
3            abcdefghij abcdefghij MTD: 12 2015     UNKNOWN       0           0             2                0
4           1ek4nd2 (4)    1ek4nd2      12 2015     UNKNOWN       0           0             0                0
5                             <NA>      12 2015       LARGE       0      219768             0                0
6            abcdefghij abcdefghij      12 2015     UNKNOWN       0           0             2                0
  Weep Amount Weep.Rate Overall.Weep.Rate WALS.Rate RET OPT Retlisher Placement.Type Platform.Type Geography
1    0      0         0                 0         0   0   0      <NA>           <NA>          <NA>      <NA>
2    0      0         0                 0         0   0   0      <NA>           <NA>          <NA>      <NA>
3    0      0         0                 0         0   0   0      <NA>           <NA>          <NA>      <NA>
4    0      0         0                 0         0   0   0      <NA>           <NA>          <NA>      <NA>
5    0      0         0                 0         0   0   0      <NA>           <NA>          <NA>      <NA>
6    0      0         0                 0         0   0   0      <NA>           <NA>          <NA>      <NA>
  Type1
1  <NA>
2  <NA>
3  <NA>
4  <NA>
5  <NA>
6  <NA>

1 个答案:

答案 0 :(得分:2)

这是一个简单的子集解决方案。做你正在寻找的事情的众多方法之一。这会解决您的问题吗?

df=data.frame(YEAR= c(2015, 2014, 2015, 2015, 2013), 
     MONTH=c(12,12,12,11,10),
     Retlisher=as.factor(c(NA,NA, 15,15,16)))


 df=df[(df$MONTH == 12 & df$YEAR==2015 & !is.na(df$Retlisher)) | 
    (!df$MONTH ==12) | (!df$YEAR == 2015),]

> df
  YEAR MONTH Retlisher
2 2014    12      <NA>
3 2015    12        15
4 2015    11        15
5 2013    10        16