[R] Replace values based on neither condition

Luigi Marongiu m@rong|u@|u|g| @end|ng |rom gm@||@com
Fri Oct 28 13:04:49 CEST 2022


Perfect, thank you!

On Fri, Oct 28, 2022 at 11:53 AM Rui Barradas <ruipbarradas using sapo.pt> wrote:
>
> Às 10:43 de 28/10/2022, Luigi Marongiu escreveu:
> > Hello,
> > I have a data frame with a string column. All data that are neither
> > "POS" nor "NEG" should've replaced by an NA. How can I implement that
> > (even with extra libraries)? My attempts actually wipe out POS and
> > NEG...
> > Thank you
> >
> > ```
> > df = data.frame(a = 1:5, b = c("",      "31.35", "POS",   "20.61", "NEG"),
> >                  stringsAsFactors = F)
> > df$b[!(df$b == "POS") & (df$b == "NEG")] = NA
> > df$b[(df$b == "POS") | (df$b == "NEG")] = NA
> > ```
> >
>
> Hello,
>
> Here is a way.
> Use `%in%` to get the values equal to either "POS" or "NEG", negate its
> result and function `is.na<-` assigns NA's.
>
>
> df = data.frame(a = 1:5, b = c("", "31.35", "POS", "20.61", "NEG"),
>                  stringsAsFactors = FALSE)
>
> is.na(df$b) <- !df$b %in% c("POS", "NEG")
> df
> #>   a    b
> #> 1 1 <NA>
> #> 2 2 <NA>
> #> 3 3  POS
> #> 4 4 <NA>
> #> 5 5  NEG
>
>
> Hope this helps,
>
> Rui Barradas



-- 
Best regards,
Luigi



More information about the R-help mailing list