[R] Select dataframe row containing a digit
Bert Gunter
bgunter@4567 @end|ng |rom gm@||@com
Wed Nov 30 17:03:26 CET 2022
I just noticed that I forgot about the "" <-> NA clause. So my "onego"
solution should be:
df <- ## to assign back to df or perhaps a new frame
within(df, val <-
ifelse(val == "", NA,
ifelse(grepl("P|Y", val, ignore.case = TRUE), "POS",
ifelse(grepl("N", val, ignore.case = TRUE), "NEG","NUM"))))
## and this then gives for val:
[1] NA "POS" "POS" "POS" "POS" "NUM" "NEG" "NEG" "NUM" "NUM"
-- Bert
On Wed, Nov 30, 2022 at 7:25 AM Bert Gunter <bgunter.4567 using gmail.com> wrote:
> ... 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 using 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 using 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]]
More information about the R-help
mailing list