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

Marcus Mund marcus.mund at uni-jena.de
Wed Jul 27 16:52:41 CEST 2011


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
-- 
Dipl.-Psych. Marcus Mund
Friedrich-Schiller-University Jena
Institute for Psychology
Department of Personality Psychology and Psychological Assessment
Humboldtstraße 11/Raum 111
07743 Jena, Germany

Tel.: +49 3641/9-45 960
Mail: marcus.mund at uni-jena.de
Fingerprint: 6B15F90EA7752D9E327A055427F4F5DC255188C4



More information about the R-help mailing list