[R] replacing elements of vector through elements of another vector

Marc Schwartz marc_schwartz at me.com
Wed Jul 27 17:38:56 CEST 2011


On Jul 27, 2011, at 9:52 AM, Marcus Mund wrote:

> Hello everybody,
> 
> I hope this question is not too silly but I'm almost going crazy about
> that and could not find a solution.
> 
> I have two variables, say A and B and I would like to combine them in C.
> In particular I want a C-value of B when B is not NA and the A value in
> case that B is NA:
> 
> A   B   C
> 2   NA  2
> 3   4   4
> NA  3   3
> 4   1   1
> 2   NA  2
> 1   4   4
> NA  NA  NA
> 5   3   3
> 4   1   1
> 
> I tried something like:
> 
> C <- B #assigning variable B to variable C
> C[is.na(B) & A >= 0] <- A #using value of A in case that B is na
> 
> but this results in an error message about the unequal length of the
> replacement and what has to be replaced...
> 
> I guess I am too deep in the problem to see the (probably) easy
> solution, hence any hints and advices are appreciated.
> 
> Thank you very much!
> 
> Marcus



Something like this:

> DF
   A  B
1  2 NA
2  3  4
3 NA  3
4  4  1
5  2 NA
6  1  4
7 NA NA
8  5  3
9  4  1


> with(DF, ifelse(!is.na(B), B, A))
[1]  2  4  3  1  2  4 NA  3  1


HTH,

Marc Schwartz



More information about the R-help mailing list