vendredi 24 avril 2020

R: How to loop or lapply over rows in one df and use the information in another df

I have a df with testcases (eg if X = 1 and Y=0 then cat= '3'), and an additional dataframe with values to be tested

df <- data.frame('tc' = c('X==1 & Y!=1 ','X==0 & Y!=1','X==1 & Y==1'), "cat" = 1:3)
Data <- data.frame(X = c('1','0', '1','1', '1'), Y = c('1','0', '1','0', '1'))

I can currently only test for one testcase at the time by using

#first testcase
Data <- within(Data, cat_test <- ifelse((X==1 & Y!=1 ), paste(df$cat[1]), 0))
table(Data$cat_test )

#second testcase
Data <- within(Data, cat_test <- ifelse((X==0 & Y!=1 ), paste(df$cat[2]), Data$cat_test))
table(Data$cat_test )

#...and so on...

I would like to use lapply or similar to loop over the dataframe and test each testcase, something like

Data <- within(Data, test <- ifelse(paste(df$tc), paste(df$cat), Data$test))

Is that possible?

Aucun commentaire:

Enregistrer un commentaire