[R] combining two columns into one column despite NAs

Sarah Goslee sarah.goslee at gmail.com
Fri Feb 25 02:37:31 CET 2011


What about:

ifelse(is.na(x), y, x)

as long as x and y are always the same where one is not NA.

Sarah

On Thu, Feb 24, 2011 at 7:53 PM, Andrew Anglemyer
<andrew.anglemyer at gmail.com> wrote:
> Thanks!  Unfortunately, in my effort to simply the question, I didn't really
> adequately describe the problem.  This solution is perfect in the numeric
> case I presented, but what about in the case of character classes!  Let me
> try again:
>
> I have
>>character.data
>           id     x        y
>       1   1    "a"    NA
>       2   2    "b"     "b"
>       3   3    "c"      "c"
>       4   4   NA      "d"
>
>
> And I want first
>>new.character.data
>           id     x        y        z
>       1   1    "a"    NA      "a"
>       2   2    "b"     "b"     "b"
>       3   3    "c"      "c"    "c"
>       4   4   NA      "d"     "d"
>
> Thanks again!
>
>
>
>
> On Thu, Feb 24, 2011 at 4:27 PM, Ista Zahn <izahn at psych.rochester.edu>wrote:
>
>> 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
>>
>


-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list