samedi 13 novembre 2021

Matching values of two data frames based on multiple conditions in R

I have a two datasets

cycle <- c(160, 150, 158, 180)
split1 <- c(2, 4, 6, 8)
split2 <- c(10, 12, 14, 16)
df1 <- data.frame(cycle, split1, split2)
df1
  cycle split1 split2
1   160      2     10
2   150      4     12
3   158      6     14
4   180      8     16

cycle <- c(160,150,190,180,161,150,140,179)
split1 <- c(2,4,12,8,2,4,32,8)
split2 <- c(10, 12, 18, 16, 10, 12, 21, 16)
df2 <- data.frame(cycle, split1, split2)
df2
  cycle split1 split2
1   160      2     10
2   150      4     12
3   190     12     18
4   180      8     16
5   161      2     10
6   150      4     12
7   140     32     21
8   179      8     16

I want to match and label the values of df1 and df2 based on two conditions:

1- If the values of all three columns i.e cycle, split1, and split2 are exactly the same then assign a row with the label "Same" otherwise "Different".

2- If the difference of only cycle value from df1 and df2 is +1 or -1 and the rest of the row values are the same then assign a row with the label "Same" otherwise "Different".

The output should look like this

  cycle split1 split2      Type
1   160      2     10      Same
2   150      4     12      Same
3   190     12     18 Different
4   180      8     16      Same
5   161      2     10      Same
6   150      4     12      Same
7   140     32     21 Different
8   179      8     16      Same

Any idea how to do that efficiently?

Thank you in advance.

Aucun commentaire:

Enregistrer un commentaire