mercredi 21 juillet 2021

Multiple ifelse function inside a mutate in R

I am trying to create a new column, that looks into whether the column 1 in dataframe A matches to column 1 in dataframe B, and if is there a match to have the value in column output in dataframe B. If column 1 in dataframe A does not a find a match in column 1 in dataframe B. To look at whether there is match between column 2 in dataframe A and column 2 dataframe B, and if there is a match to have the output 2 from dataframe B. If there is no matches then for it to be zero.

This is my attempt, I think it semi works but it gives me a lot of NAs, a lot of these NAs are false because there is match in columns between the dataframes but it still comes up as NA. Any help would be appreciated.

 dataframeA<-dataframeA %>% mutate(newcolumn=ifelse(column1 %in% dataframeB$column1, dataframeB$output, ifelse(column2 %in% dataframeB$column2, dataframeB$output2,NA)))

I tried to use case_when but this doesn't work because I want the output value to be from a column.

Thank you

Aucun commentaire:

Enregistrer un commentaire