user3302113
user3302113

Reputation: 27

recoding variable into two new variables in R

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!

Upvotes: 0

Views: 111

Answers (3)

Paul Hiemstra
Paul Hiemstra

Reputation: 60924

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.

Upvotes: 1

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

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

Upvotes: 1

Christopher Louden
Christopher Louden

Reputation: 7582

You can use ifelse() for that:

a1 <- ifelse(B == 1, A, NA)

Upvotes: 3

Related Questions