简体   繁体   中英

Removing NA from Column based on Condition in R

I have a dataframe where based on the condition of two of the columns, I want to remove the rows with NA's from a different column.

I tried this but it doesn't seem to be working:

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

When I try this, R crashes. This is the original dataframe:

  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>

Here is a simple subsetting solution. One of many ways to do what you are looking for. Does this solve your problem?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM