对于循环错误:替换的长度为零

我试图根据一列在两个数据帧之间匹配值,然后将相应的值分配给其中一个数据帧。这是数据的样子

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]])
}

但是,我得到以下错误代码:

Error: replacement has length zero

我到处都看过了,但不知道这意味着什么或错误来自哪里。有什么建议么?

评论