user3262756
user3262756

Reputation: 679

Combine character columns into new column

I'd be very grateful if you could help me with the following as after a few tests I haven't still been able to get the right outcome.

I've got this data:

dd_1 <- data.frame(ID = c("1","2", "3", "4", "5"),
                 Class_a = c("a",NA, "a", NA, NA),
                 Class_b = c(NA, "b", "b", "b", "b"))

And I'd like to produce a new column 'CLASS':

dd_2 <- data.frame(ID = c("1","2", "3", "4", "5"),
                 Class_a = c("a",NA, "a", NA, NA),
                 Class_b = c(NA, "b", "b", "b", "b"),
                 CLASS = c("a", "b", "a-b", "b", "b"))

Thanks a lot!

Upvotes: 2

Views: 4336

Answers (3)

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

Here's a short solution with apply:

dd_2 <- cbind(dd_1, CLASS = apply(dd_1[2:3], 1, 
                                  function(x) paste(na.omit(x), collapse = "-")))

The result

  ID Class_a Class_b CLASS
1  1       a    <NA>     a
2  2    <NA>       b     b
3  3       a       b   a-b
4  4    <NA>       b     b
5  5    <NA>       b     b

Upvotes: 0

talat
talat

Reputation: 70246

Another option:

dd_1$CLASS <- with(dd_1, ifelse(is.na(Class_a), as.character(Class_b),
                               ifelse(is.na(Class_b), as.character(Class_a), 
                                        paste(Class_a, Class_b, sep="-"))))

This way you would check if any of the classes is NA and return the other, or, if none is NA, return both separated by "-".

Upvotes: 1

gagolews
gagolews

Reputation: 13046

Here it is:

tmp <- paste(dd_1$Class_a, dd_1$Class_b, sep='-')
tmp <- gsub('NA-|-NA', '', tmp)
(dd_2 <- cbind(dd_1, tmp))

First we concatenate (join as strings) the 2 columns. paste treats NAs as ordinary strings, i.e. "NA", so we either get NA-a, NA-b, or a-b. Then we substitute NA- or -NA with an empty string.

Which results in:

##   ID Class_a Class_b tmp
## 1  1       a    <NA>   a
## 2  2    <NA>       b   b
## 3  3       a       b a-b
## 4  4    <NA>       b   b
## 5  5    <NA>       b   b

Upvotes: 2

Related Questions