JohnD
JohnD

Reputation: 121

R: creating a new variable by merging the contents of two variables in

I have a dataframe a with two variables that represents two types of people. The way the df is set now is that for one variable there are NAs when the values don't represent person A and in the second variable there are NAs where the values don't represent person b. I want to combine these two variables so that I just have 1 variable.

The DF looks something like this:

Total <- rep(c(1, NA, NA, 5) , 1)
Total2 <-rep( c(NA, 8,9,NA), 1)
data <- data.frame(Total, Total2)

I would like to add a third variable that looks like this:

  Total <- rep(c(1, NA, NA, 5) , 1)
    Total2 <-rep( c(NA, 8,9,NA), 1)
   All_var = rep(c(1,8,9,5), 1)
   data <- data.frame(Total, Total2, All_var)

I've tried this, but I just get a new variable with the same values as Total.

data$All_var=data$Total
data$All_var[is.na(data$Total)]=data$Total2[is.na(data$Total)]

Thanks.

Upvotes: 0

Views: 1122

Answers (1)

Ben
Ben

Reputation: 30474

In base R try:

data$newvar <- replace(data$Total, is.na(data$Total), data$Total2[is.na(data$Total)])

Or using coalesce with dplyr:

library(dplyr)

data %>%
  mutate(newvar = coalesce(Total, Total2))

Upvotes: 1

Related Questions