Home > Mobile >  Create new list in R based on matching values from two data.frames
Create new list in R based on matching values from two data.frames

Time:12-07

I have a data frame that looks like:

df<-data.frame(x=c('x1','x2','x3','x4','x5'),y=c(1,2,3,4,5))
df2<-data.frame(x=c('x3','x5'),y=c(3,5))

df3<-merge(df,df2,by="x")

How do I create a list of 0's and 1's based on if the x values from df were matched to the x values from df2? For example, the new data frame would look like:

newdf<-data.frame(x=c('x1','x2','x3','x4','x5'),y=c(1,2,3,4,5),match=c(0,0,1,0,1)

CodePudding user response:

Using data.table (matching on x and y):

library(data.table)
setDT(df)
df[, match := 0L]
df[df2, on = .(x, y), match := 1L]
#     x y match
# 1: x1 1     0
# 2: x2 2     0
# 3: x3 3     1
# 4: x4 4     0
# 5: x5 5     1

CodePudding user response:

A base solution to recreate your newdf:

newdf <- df
newdf$match <- ifelse(df$x %in% df2$x, 1, 0)

Or, using tidyverse syntax:

library(tidyverse)

df %>%
  mutate(match = ifelse(x %in% df2$x, 1, 0))
  • Related