-1

I want to ask, how can I make a new column in a data.frame in R by merging 2 columns (with categorical values) with all rows in the file. Following example is showing alternate categorical conditions in column_1 and column_2 how could I make column_3 by merging columns_1 and column_2? Moreover, in 4th row both columns have values, so in this case what would be in column_3. (NA are blanks).

Column_1 Column_2  Column_3
1          NA
NA          2
2           NA
NA          1
1           2
mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194
Amara
  • 21
  • 1
  • 4

1 Answers1

0

Welcome to StackOverflow! Please consider providing a reproducible example to make it easier for us to help you. E.g.

df <- data.frame(Column_1 = c(1, NA, 2, NA, 1), Column_2=c(NA, 2, NA, 1, 2))

You could use ifelse here if you just wanted to stick to base R.

df$Column_3 = ifelse(is.na(df$Column_1), df$Column_2,
                     ifelse(is.na(df$Column_2), df$Column_1,
                            df$Column_1))

This says "if Column 1 is NA, use column 2. Otherwise, if Column 2 is NA, use column 1. Otherwise (both are not NA), use Column 1".

You need to decide what you want to do if both columns are not-NA.

If you want to skip some typing (of df$) you can use with

df$Column_3 = with(df,
                   ifelse(is.na(Column_1), Column_2,
                          ifelse(is.na(Column_2), Column_1,
                                 Column_1)))
Community
  • 1
  • 1
mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194