Home > database >  using values of two columns to populate a separate column
using values of two columns to populate a separate column

Time:07-19

I have a dataset that looks like this

data <- data.frame(parent = c(1, 1, 2, 2, 1, 2, 1, 1),
                   child = c(1, 2, 2, 1, 2, 2, 1, 2))
  parent child
    1     1
    1     2
    2     2
    2     1
    1     2
    2     2
    1     1
    1     2

Based on parent and child, I want to populate a new column dyad.

If parent equals 1 and child equals 1, dyad equals 1 if parent equals 1 and child equals 2, dyad equals 2; if parent equals 2 and child equals 2, dyad equals 3; and if parent equals 2 and child equals 1, dyad equals 4.

My final desired output is:

 parent child dyad
   1     1    1
   1     2    2
   2     2    3
   2     1    4
   1     2    2
   2     2    3
   1     1    1
   1     2    2

Thank you for your help!

CodePudding user response:

Create a keyval dataset and do a join

library(dplyr)
keydat <- tibble(parent = c(1, 1, 2, 2), child = c(1, 2, 1, 2),
     dyad = c(1, 2, 4, 3))
left_join(data, keydat)

-output

  parent child dyad
1      1     1    1
2      1     2    2
3      2     2    3
4      2     1    4
5      1     2    2
6      2     2    3
7      1     1    1
8      1     2    2

CodePudding user response:

With dplyr::case_when()

library(tidyverse)

data <- tibble(parent = c(1, 1, 2, 2, 1, 2, 1, 1),
                   child = c(1, 2, 2, 1, 2, 2, 1, 2))

data %>%  
  mutate(dyad = case_when(parent == 1 & child == 1 ~ 1, 
                          parent == 1 & child == 2 ~ 2, 
                          parent == 2 & child == 1 ~ 3, 
                          TRUE ~ 4))

# A tibble: 8 × 3
  parent child  dyad
   <dbl> <dbl> <dbl>
1      1     1     1
2      1     2     2
3      2     2     4
4      2     1     3
5      1     2     2
6      2     2     4
7      1     1     1
8      1     2     2
  • Related