Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace negative values by NA values

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
}
like image 418
Tika Ram Gurung Avatar asked Feb 24 '15 12:02

Tika Ram Gurung


People also ask

How do you handle negative values in a data set?

A common technique for handling negative values is to add a constant value to the data prior to applying the log transform. The transformation is therefore log(Y+a) where a is the constant. Some people like to choose a so that min(Y+a) is a very small positive number (like 0.001).

How do you change a negative number to a positive in R?

How do you change negative numbers to positive in R? To change the ne gative numbers to positive in R we can use the <code>abs()</code> function. For example, if we have the vector <code>x</code> containing negative numbers, we can change them to positive numbers by typing <code>abs(x)</code> in R.


2 Answers

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))
like image 197
talat Avatar answered Sep 27 '22 22:09

talat


You could try this:

sample <- c(1, -2, NA)
sample[sample < 0] <- NA
sample
[1]  1 NA NA

Or if you're using a data.frame (suppose it's called df):

df$q[df$q < 0] <- NA
like image 23
codingEnthusiast Avatar answered Sep 27 '22 23:09

codingEnthusiast