Here are two df
s of example data:
df1
ID First.seen Last.seen
A10 2015-09-07 2015-09-16
A11 2015-09-07 2015-09-19
df2
ID First_seen Last_seen
A1 2015-09-07 0
A10 2015-09-07 0
I want to fill df2$Last_seen
if the ID
is common in both dfs
. Note that in the real data I have several IDs in both dfs. I've tried with for
loop but I just get numerical values:
for (i in 1:nrow(df2)){
if (df2$ID[i] %in% df1$ID) {
df2$Last_seen[i] <- df1$Last.seen[df1$ID == df2$ID[i]]
}else{
df2$Last_seen[i] <- 0
}
}
I found this answer to the same question that uses seq_along
but I get a result of df1$Last_seen[i] == 1
when I apply this code:
for (i in seq_along(1:nrow(df2))){
if (df2$ID[i] %in% df1$ID) {
df2$Last_seen[i] <- df1$Last.seen[df1$ID == df2$ID[i]]
}else{
df2$Last_seen[i] <- 0
}
}
Any suggestions on how to use it properly?