suresh
suresh

Reputation: 59

Wrong replacement in R

I have two variables A and B

a              b
234323432      NA
234324343      NA
238432788      NA
6786686        576575 
97892734       NA
87236488       NA
234683246      NA

I want to replace b with a whenver b is NA I tried with

la2$b[is.na(la2$b)] <- la2$a

first three NA's are replaced correctly but after 4th row the 5th row of b is replace by 4th row of a. Is there any specific reason for wrong replacement.

a              b
234323432      234323432
234324343      234324343
238432788      238432788
6786686        576575 
97892734       6786686
87236488       97892734
234683246      87236488

expected output below

a              b
234323432      234323432
234324343      234324343
238432788      238432788
6786686        576575 
97892734       97892734
87236488       87236488
234683246      234683246

Upvotes: 1

Views: 26

Answers (1)

RHertel
RHertel

Reputation: 23818

To match the indices of the two vectors, you can try

la2$b[is.na(la2$b)] <- la2$a[is.na(la2$b)]
#          a         b
#1 234323432 234323432
#2 234324343 234324343
#3 238432788 238432788
#4   6786686    576575
#5  97892734  97892734
#6  87236488  87236488
#7 234683246 234683246

If computation time matters (in the case of large data sets), it should be preferable to compute the indices once and store them in a vector idx, as pointed out by @docendodiscimus.

idx <- is.na(la2$b)
la2$b[idx] <- la2$a[idx]

data

la2 <- structure(list(a = c(234323432L, 234324343L, 238432788L, 6786686L, 
            97892734L, 87236488L, 234683246L), b = c(NA, NA, NA, 576575L, 
            NA, NA, NA)), .Names = c("a", "b"), class = "data.frame", 
            row.names = c(NA, -7L))

Upvotes: 3

Related Questions