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

David Winsemius dwinsemius at comcast.net
Wed Jul 27 17:52:36 CEST 2011


On Jul 27, 2011, at 10: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

Just use:

  C[is.na(B) ] <- A[is.na(B) ]

# doesn't matter what A is. Or if it does, then use same logical vecot  
index on both sides

You need to have is.na(B) on both sides to get the vector assignments  
to match up. That is what the error message is telling you.

>
> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list