Search code examples
rcombinationssequencedata-manipulationdata-cleaning

Combine two sequences of data


I have two sequences of data (with five variables in each sequence) that I want to combine accordingly into one using this rubric:

variable sequence 1   variable sequence 2     variable in combined sequence     
        0                      0                            1
        0                      1                            2
        1                      0                            3
        1                      1                            4

Here are some example data:

set.seed(145)
mm <- matrix(0, 5, 10)
df <- data.frame(apply(mm, c(1,2), function(x) sample(c(0,1),1)))
colnames(df) <- c("s1_1", "s1_2", "s1_3", "s1_4", "s1_5", "s2_1", "s2_2", "s2_3", "s2_4", "s2_5")
> df
  s1_1 s1_2 s1_3 s1_4 s1_5 s2_1 s2_2 s2_3 s2_4 s2_5
1    1    0    0    0    0    0    1    1    0    0
2    1    1    1    0    1    1    0    0    0    0
3    1    1    0    0    0    1    1    0    1    1
4    0    0    1    0    1    1    0    1    0    1
5    0    1    0    0    1    0    0    1    1    0

Here s1_1 represents variable 1 in sequence 1, s2_1 represents variable 2 in sequence 2, and so on. For this example, s1_1=1 and s2_1=0, the variable 1 in combined sequence would be coded as 3. How do I do this in R?


Solution

  • Here's a way -

    return_value <- function(x, y) {
      dplyr::case_when(x == 0 & y == 0 ~ 1, 
                       x == 0 & y == 1 ~ 2, 
                       x == 1 & y == 0 ~ 3, 
                       x == 1 & y == 1 ~ 4)
    }
    sapply(split.default(df, sub('.*_', '', names(df))), function(x) 
           return_value(x[[1]], x[[2]]))
    
    #     1 2 3 4 5
    #[1,] 3 2 2 1 1
    #[2,] 4 3 3 1 3
    #[3,] 4 4 1 2 2
    #[4,] 2 1 4 1 4
    #[5,] 1 3 2 2 3 
    

    split.default splits the data by sequence and using sapply we apply the function return_value to compare the two columns in each dataframe.