mardi 3 novembre 2020

subset a dataframe on multiple conditions in R

My dataset has several variables and I want to build a subset as well as create new variables based on those conditions

S1 S2 H1 H2 Month1 Year1 Month2 Year2
16 17 81 70  09   2017   07      2017
17 16 80 70  08   2017   08      2016
14 16 81 81  09   2016   05      2016
18 15 70 81  07   2016   09      2017
17 16 80 80  08   2016   05      2016
18 18 81 70  05   2017   04      2016

I want to subset such that if S1=16,17,18 and H1=81,80 then I create a new variable Hist=H1 , date=paste(Month1,Year1) Sip = S1 Same goes for set of S2, H2 . My output should be: [ The first 4 rows comes for sets of S1,H1, Month1,Year2 and last 2 rows comes from S2,H2,Month2,Year2

Hist Sip Date
81   16  09-2017
80   17  08-2017
80   17  08-2016
81   18  05-2017
81   16  05-2016
80   16  05-2016

I tried using the mutate and ifelse condition but failed. In the original data I have 10 sets of such columns ie S1-S10, H1-H10, Month1_-Month10....

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire