0

I have a variable A containing continuous numeric values and a binary variable B. I would like to create a new variable A1 which contains the same values as A if B=1 and missing values (NA) if B=2. Many thanks!

3
  • 2
    Please can you show some example data and results? Commented Feb 12, 2014 at 14:56
  • 2
    Folks - lets be gentle with new users to SO (i.e. the -1's). This question is quite clear even though evidence of previous attempts is lacking. Commented Feb 12, 2014 at 15:13
  • Besides ifelse, I guess you could also just index A through B, i.e. A[B == 2] <- NA. Commented Feb 12, 2014 at 15:41

3 Answers 3

3

You can use ifelse() for that:

a1 <- ifelse(B == 1, A, NA)
Sign up to request clarification or add additional context in comments.

Comments

1

Here's a simple and efficient approach without ifelse:

A <- 1:10
# [1]  1  2  3  4  5  6  7  8  9 10
B <- rep(1:2, 5)
# [1] 1 2 1 2 1 2 1 2 1 2
A1 <- A * NA ^ (B - 1)
# [1]  1 NA  3 NA  5 NA  7 NA  9 NA

Comments

1

You can use ifelse for this:

A = runif(100)
B = sample(c(0,1), 100, replace = TRUE)
B1 = ifelse(B == 1, A, NA)

You can even leave out the == 1 as R interprets 0 as FALSE and any other number as TRUE:

B1 = ifelse(B, A, NA)

Although the == 1 is both more flexible and makes it more clear what happens. So I'd go for the first approach.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.