I have dataframes DF1
and DF2
:
DF1 <- data.frame(color = factor(c("Blue", "Brown", "Blue", "Brown", "Blue", "Brown", "Blue", "Brown")),
location = factor(c("California", "Nevada", "Nevada", "California", "Arizona", "Arizona", "California", "Nevada")),
respondent = factor(c("R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8")))
DF2 <- data.frame(shape = factor(c("Square", "Square", "Round", "Square", "Round", "Round", "Square", "Round", "Square", "Square")),
location = factor(c("California", "Nevada", "Arizona", "California", "California", "Arizona", "California", "Nevada", "Arizona", "California")),
respondent = factor(c("A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "A10")))
I want to merge them and create dataframe DF3
, and would like to "match" the values of the factor location
from the two original dataframes.
The following results in a dataframe in a format I want, but with two different location
factors (location.y
and location.x
):
DF3 <- merge(data.frame(DF1, row.names=NULL), data.frame(DF2, row.names=NULL),
by = 0, all = TRUE)[-1]
I would like to avoid that, and have only one location
factor with the locations from both dataframes matched, but merging the dataframes by location results in duplication of values in DF3
:
DF3 <- merge(data.frame(DF1, row.names=NULL), data.frame(DF2, row.names=NULL),
by = "location", all = TRUE)[-1]
Is there a better way to merge the dataframes?