[R] Select dataframe row containing a digit

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Wed Nov 30 15:38:16 CET 2022


À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



More information about the R-help mailing list