aodell
aodell

Reputation: 11

R: Create new column in dataframe from existing columns using conditions

I have a dataframe with two numeric columns that I'd like to use to create and populate a third column using conditions.

Here is an example of my dataframe:

- A B
1 123 134
2 343 NA
3 123 145
4 NA 243
5 NA NA
6 NA 293

I'd like to create a new column based upon the values in columns A and B and these conditions:

Example output:

A B C
1 123 134 123
2 343 NA 342
3 123 145 123
4 NA 243 243
5 NA NA NA
6 NA 293 243

Upvotes: 1

Views: 758

Answers (2)

akrun
akrun

Reputation: 887811

Another option is coalesce

df1 <- df1 %>% 
    mutate(C = coalesce(A, B))

-output

df1
#   A   B   C
#1 123 134 123
#2 343  NA 343
#3 123 145 123
#4  NA 243 243
#5  NA  NA  NA
#6  NA 293 293

Or using fcoalesce from data.table

library(data.table)
setDT(df1)[, C := fcoalesce(A, B)]

data

df1 <- 
structure(list(A = c(123L, 343L, 123L, NA, NA, NA), B = c(134L, 
NA, 145L, 243L, NA, 293L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

Upvotes: 1

Anoushiravan R
Anoushiravan R

Reputation: 21938

You can use the following solution:

library(dplyr)

df %>%
  rowwise() %>%
  mutate(C = case_when(
    !is.na(A) ~ A,
    is.na(A) & !is.na(B) ~ B,
    is.na(A) & is.na(B) ~ NA_integer_
  ))

# A tibble: 6 x 3
# Rowwise: 
      A     B     C
  <int> <int> <int>
1   123   134   123
2   343    NA   343
3   123   145   123
4    NA   243   243
5    NA    NA    NA
6    NA   293   293

Data

structure(list(A = c(123L, 343L, 123L, NA, NA, NA), B = c(134L, 
NA, 145L, 243L, NA, 293L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

Upvotes: 1

Related Questions