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.
EDIT here is some sample data from the help of @bloxx
dataframeA<- data.frame(Column1 = c("a", "b", "c", "f"),
Column2 = c("a", "a", "a", "f"))
dataframeB<- data.frame(Column1 = c("b", "b", "c", "e", "f", "g", "h"),
Column2 = c("a", "b", "a", "e"),
Output = c("B", "B", "B", "B","B","B","B"),
Output2 = c("D", "D", "D", "D"))
dataframeA <- dataframeA %>%
mutate(new_variable = ifelse(Column1 %in% dataframeB$Column1,
dataframeB$Output,
ifelse(Column2 %in%
dataframeB$Column2,dataframeB$Output2, 0 )))
In my dataset, dataframeB has different lengths, but even if make it the same length, there is a lot of NAs.
Thank you