[R] combining two columns into one column despite NAs

Ista Zahn izahn at psych.rochester.edu
Fri Feb 25 01:27:24 CET 2011


I think the easiest way is probably

data$z <- rowMeans(data[, c("x", "y")], na.rm=TRUE)

Best,
Ista

On Fri, Feb 25, 2011 at 12:12 AM, Andrew Anglemyer
<andrew.anglemyer at gmail.com> wrote:
> I am trying to combine two columns in a data frame into one column.  Some
> values in either column are missing, but not in the same row for the two
> different columns.  Additionally, when both columns in a row contain data,
> the data are identical.  I want a new column with the identical data or the
> data from the column with observed data.  For example:
>
> I have
>>data
>           id   x    y
>       1   a   1   NA
>       2   b   2    2
>       3   c   3    3
>       4   d  NA  4
>
> And I want
>>new.data
>           id   x    y     z
>       1   a   1   NA   1
>       2   b   2    2     2
>       3   c   3    3     3
>       4   d  NA  4     4
>
> I've looked through the help and there are column combining solutions, but
> they don't seem to work well for this solution.
> Thanks for any help!
> Andy
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



-- 
Ista Zahn
Graduate student
University of Rochester
Department of Clinical and Social Psychology
http://yourpsyche.org



More information about the R-help mailing list