Changing variable value

2

Good evening colleagues:

I have a numeric variable:

  

cv1 [1:10] [1] 0 0 108919 4152 317 334403 0 35092   12762 NA

I want to create the variable cv2, replacing the absolute values of zero (0) with "NA". Using the "gsub" function it replaces ALL zero numerals, including numbers that have zero in the middle of them: (108919, 334403, 35092)

  

cv2 = gsub ("0", NA, cv1)

     

cv2 [1:10]    [1] NA NA NA "4152" "317" NA NA NA "12762" NA

How could I only change the absolute values from zero to NA. Can anyone help me?

    
asked by anonymous 10.03.2018 / 23:38

2 answers

4

You can create an index to find out which positions of cv1 have 0 ,

ind  <- which(cv1 == 0)

then just replace with NA :

cv2 <- cv1
cv2[ind] <- NA
    
11.03.2018 / 00:12
1

One possibility is to use the is.na<- function.

First, read the question data.

cv1 <- scan(text = "0 0 108919 4152 317 334403 0 35092 12762 NA")

Now, turn the zero values into NA .

cv2 <- cv1
is.na(cv2) <- cv2 == 0
cv2
#[1]     NA     NA 108919   4152    317 334403     NA  35092  12762     NA

As in Rafael Cunha's response, I modified a copy of the cv1 vector, keeping the original. This form with is.na<- has the advantage of not creating an extra vector, such as the ind vector in Rafael Cunha's response.

    
12.03.2018 / 15:16