Replace negative values by NA values

Tika Ram Gurung picture Tika Ram Gurung · Feb 24, 2015 · Viewed 17.1k times · Source

I have positive, negative and NA values in a Table, I need to replace negative values by NA values. Positive and NA values should remain as they are in Table. My Data set is similar to the one below:

NO. q
1   NA
2   NA
3   -133.6105198
4   -119.6991209
5   28.84460104
6   66.05345087
7   84.7058947
8   -134.4522694
9   NA
10  NA
11  73.20465643
12  -69.90723514
13  NA
14  69.70833003
15  65.27859906

I tried this:

if (q>0) {
    q=NA
} else {
    q=q
}

Answer

talat picture talat · Feb 24, 2015

Or use replace:

> df$q2 <- replace(df$q, which(df$q < 0), NA)
> df
   NO.          q       q2
1    1         NA       NA
2    2         NA       NA
3    3 -133.61052       NA
4    4 -119.69912       NA
5    5   28.84460 28.84460
6    6   66.05345 66.05345
7    7   84.70589 84.70589
8    8 -134.45227       NA
9    9         NA       NA
10  10         NA       NA
11  11   73.20466 73.20466
12  12  -69.90724       NA
13  13         NA       NA
14  14   69.70833 69.70833
15  15   65.27860 65.27860

Or with data.table:

library(data.table)
setDT(df)[q < 0, q := NA]

Or with replace in a dplyr pipe:

library(dplyr)
df %>% mutate(q = replace(q, which(q<0), NA))