# Comparing 2 data frames, if value is present replace with 1 or else 0

nrow(df1$v1) = 63849 nrow(df2$v2) = 3244
ifelse(df1$v2 == df$v1, 1, 0)


I know this is an easy question but I tried different procedures but none of them are useful,

for(i in 1:nrow(df2)){
for(j in 1:nrow(df1)){
if(df2$v1[i] == df1$v2[j]){
df1$v2<- 1 } df1$v2 <- 0
}
}


This does the job but it take quiet sometime to get the job done.

Other Methods: Method 1:

df1$v2 <- ifelse(df2$v1 %in% df1$v1, 1,0 ) Error in $<-.data.frame(*tmp*, v2 , value = c(1, 1, 1, 1, 1, 1,  :


replacement has 3244 rows, data has 63849

Method 2:

df1$v2 <- ifelse(do.call(paste0, df2$v1) %in%
do.call(paste0, df1$v1), 1,0 ) summary(df1$v2)
Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
0       0       0       0       0       0


Do suggest me if you have any better solution.

## 1 Answer

Here is a way using dplyr:

require(dplyr)
X = data_frame(A=c(1,2,3,4))
Y = data_frame(B=c(5,4,6,7))

X <- X %>%
mutate(A = A %in% Y$B, A = A*1.0) #converts boolean to numeric  or using base R: X$A <- 1.0*(X$A %in% Y$B)

• the base R version is not working, Error in \$<-.data.frame(*tmp*, v2, value = c(1, 1, 1, 1, 1, 1, : replacement has 3244 rows, data has 63849 , – Toros91 Nov 17 '17 at 6:26
• The data frame that you are assigning to has to have the same rows as the one before (not after) the %in%. For A %in% B, the %in% is a boolean operation that gives you one answer for every entry in A - so the thing you're assigning to must have the same number of rows as A. In your code above you have it switched around. – tom Nov 17 '17 at 6:31
• Thank you, Job done! I tried that, thought that there is some issue, wrote that in the above code but dint know that I need to swap them. – Toros91 Nov 17 '17 at 6:34
• Can you help me by explaining a bit more on the dplyr version, I'm not very familiar with dplyr, mutate and all. if you have any good references with examples for my future reference. – Toros91 Nov 17 '17 at 6:46
• Dplyr is part of the 'Tidyverse' packages written mostly by Hadley Wickham. Here is some documentation for dplyr specifically (r4ds.had.co.nz/transform.html). The syntax is like a 'data flow' - the %>% is called a 'pipe' and your data 'flows' through it...after that, each line is a transformation, so each line in mutate assigns the A variable whatever is on the right side of the equal sign, in order. If you use R a lot I'd seriously consider learning more about dplyr/readr/ggplot2/etc. I find they make R code much easier to write and read. – tom Nov 17 '17 at 6:51