vendredi 17 juin 2016

for if else loop - fill values in column based on matching columns from separate dataframes [duplicate]

This question already has an answer here:

I have two dataframes.

df1

ID  Name   
A1  Dave
B2  Bob
C1  Sheila   
D1  Tim   


df2

ID   Focal
A1      0
B1      0
C1      0
D1      0
E1      0
F1      0

I want to fill in the "Focal" column with 1's if values in df1$ID match df2$ID.

I've tried looping it with:

for (i in 1:length(df2)){
  if (df1$ID[i] == df2$ID[i]){df2$Focal[i] = 1}
  else {df2$Focal[i] = 0}
}

but get error saying levels sets of factors are different.

Aucun commentaire:

Enregistrer un commentaire