How can I combine two string variables?

Viewed 22

I have two variables (here string1 and string2), which are open answer survey questions. Respondents can only respond to one of the two, so if one has a response, the other has to be missing. How do I combine the two variables? (in this example the variable combi).

string1 string2 combi
NA abc abc
abd NA abd
NA aba aba
abb NA abb
1 Answers

Here's a tidyverse solution:

# Reproducing your data
mydata <- tibble(
  string1 = c(NA, "abd", NA, "abb"),
  string2 = c("abc", NA, "aba", NA)
)

result <- mydata |> 
  mutate(combi = na.exclude(c(string1, string2)))

Output:

# A tibble: 4 × 3
  string1 string2 combi
  <chr>   <chr>   <chr>
1 NA      abc     abd  
2 abd     NA      abb  
3 NA      aba     abc  
4 abb     NA      aba  
Related