6

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
}
catastrophic-failure
  • 3,759
  • 1
  • 24
  • 43
Tika Ram Gurung
  • 179
  • 3
  • 3
  • 9
  • data is like this: here "q" name of column NA NA -133.6105198 -119.6991209 28.84460104 66.05345087 84.7058947 -134.4522694 NA NA 73.20465643 -69.90723514 NA 69.70833003 65.27859906 – Tika Ram Gurung Feb 24 '15 at 12:41
  • Hi and thanks for the question. Since you are a new user, you'd probably like to read the Tour and also either accept the answer that covers you the most (green tick next to each answer), or provide additional information if no answer covers you 100%. – codingEnthusiast Feb 24 '15 at 13:23

4 Answers4

12

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))
jpgard
  • 653
  • 7
  • 15
talat
  • 68,970
  • 21
  • 126
  • 157
9

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
codingEnthusiast
  • 3,800
  • 2
  • 25
  • 37
6

You could try

df1$q1 <- NA^(df1$q <0) * df1$q
df1
#   NO.          q       q1
#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 use ifelse

 with(df1, ifelse(q < 0, NA, q))

Or

 is.na(df1$q) <- df1$q < 0
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Another way of accomplishing the same thing is (now I see this is ALMOST the same as another answer by akrun, sorry for that)

daf$q = ifelse(daf$q < 0, NA_real_, daf$q)
catastrophic-failure
  • 3,759
  • 1
  • 24
  • 43