0
Follow
1
View

Combine two sequences of data

linyu3094 注册会员
2023-01-26 10:00

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.