# Possibility to put two variables into one

Hi
so I have a question concerning the possibility to sum two variables up. If you have two variables M1 and M2 in one data set, and the only difference between those is that M1 is answered by single men and M2 ist answered by married men could you put them together in M3, so that you have one variable for the sex of the person (maybe in some kind of subset) or is it impossible to combine them.

If I've understood correctly, this is exceedingly possible!

``````# set up data
dat = data.frame(M1 = 1:5, M2 = 1:5)

dat
#>   M1 M2
#> 1  1  1
#> 2  2  2
#> 3  3  3
#> 4  4  4
#> 5  5  5

# combine columns
dat\$M3 = dat\$M1 + dat\$M2

dat
#>   M1 M2 M3
#> 1  1  1  2
#> 2  2  2  4
#> 3  3  3  6
#> 4  4  4  8
#> 5  5  5 10

# drop old ones?
dat\$M1 = NULL
dat\$M2 = NULL

dat
#>   M3
#> 1  2
#> 2  4
#> 3  6
#> 4  8
#> 5 10

# tidyverse
library(tidyverse)

tibble(M1 = 1:5, M2 = 1:5) %>%
mutate(M3 = M1 + M2) %>%
select(-M1, -M2)
#> # A tibble: 5 x 1
#>      M3
#>   <int>
#> 1     2
#> 2     4
#> 3     6
#> 4     8
#> 5    10
``````

Created on 2021-12-17 by the reprex package (v2.0.1)

Next time, please provide a reproducible example.

Great, thank you so much for the input!

I created a little example to show what I meant: I added the M3 column to show what i would want to create
I hope this shows what i mean

Oh! In that case:

``````library(tidyverse)

dat = tibble(x = c(1:5, rep(NA, 5)),
y = c(rep(NA, 5), 1:5))

mutate(dat,
z = coalesce(x,y))
#> # A tibble: 10 x 3
#>        x     y     z
#>    <int> <int> <int>
#>  1     1    NA     1
#>  2     2    NA     2
#>  3     3    NA     3
#>  4     4    NA     4
#>  5     5    NA     5
#>  6    NA     1     1
#>  7    NA     2     2
#>  8    NA     3     3
#>  9    NA     4     4
#> 10    NA     5     5
``````