I'm trying to match values between two data frames based on one column, and then assign a corresponding value to one of the data frames. Here is what the data look like
head(test1)
zip dat.citystate
1 80914
2 32920
3 80914
4 80914
5 80914
6 80914
head(test2)
zip citystate
1 35004 Moody, AL
2 35005 Adamsville, AL
3 35006 Adger, AL
4 35007 Alabaster, AL
5 35010 Alexander City, AL
6 35011 Alexander City, AL
The dat.citystate
column in test1
is an empty string ""
.
I want to loop through test1
and find the city-state value from test2
that shares the same zip code, and add that to the corresponding row for test1
. Here is my for loop:
for (i in 1:nrow(test1)){
test1$dat.citystate[i] <- test2$citystate[test2$zip == test1$zip[i]])
}
However, I get the following error code:
Error: replacement has length zero
I've looked everywhere but can't figure out what this means or where the error is coming from. Any suggestions?