... or, if you wanted to do it all in one go:
within(df, val <-
ifelse(grepl("P|Y", val, ignore.case = TRUE), "POS",
ifelse(grepl("N", val, ignore.case = TRUE),
"NEG","NUM")))
## which gives
[1] "NUM" "POS" "POS" "POS"
"POS" "NUM" "NEG" "NEG" "NUM"
"NUM"
for the "val" column
-- Bert
On Wed, Nov 30, 2022 at 6:38 AM Rui Barradas <ruipbarradas at sapo.pt>
wrote:
> ?s 12:40 de 30/11/2022, Luigi Marongiu escreveu:
> > Hello,
> > I have a data frame where some lines containing strings including
digits.
> > How do I select those rows and change their values?
> >
> > In essence, I have a data frame with different values assigned to the
> > column "val". I am formatting everything to either
"POS" and "NEG",
> > but values entered as number should get the value "NUM".
> > How do I change such values?
> >
>
> Hello,
>
> Here is a way with grep.
>
>
> i <- grep("^P|^Y", df$val, ignore.case = TRUE)
> df$val[i] <- "POS"
> i <- grep("^N", df$val, ignore.case = TRUE)
> df$val[i] <- "NEG"
> i <- grep("\\d+", df$val)
> df$val[i] <- "NUM"
> is.na(df$val) <- df$val == ""
> df
>
>
> Hope this helps,
>
> Rui Barradas
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
[[alternative HTML version deleted]]