Changing variable value

Asked

Viewed 60 times

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 the numbers that have zero in the middle of them: (108919, 334403, 35092)

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

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

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

2 answers

4

You can create an index to know in which positions cv1 possess 0,

ind  <- which(cv1 == 0)

then just replace with NA:

cv2 <- cv1
cv2[ind] <- NA

1

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

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 reply, I modified a copy of the vector cv1, retaining the original.
This form, with is.na<-, has the advantage of not creating an extra vector, such as the vector ind in Rafael Cunha’s answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.