[英]For loop error: replacement has length zero
我正在尝试基于一列匹配两个数据框之间的值,然后将相应的值分配给其中一个数据框。 这是数据的样子
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
test1
中的dat.citystate
列是空字符串""
。
我想遍历test1
并从test2
中找到共享相同 zip 代码的城邦值,并将其添加到test1
的相应行。 这是我的 for 循环:
for (i in 1:nrow(test1)){
test1$dat.citystate[i] <- test2$citystate[test2$zip == test1$zip[i]])
}
但是,我收到以下错误代码:
Error: replacement has length zero
我到处都看过,但无法弄清楚这意味着什么或错误来自何处。 有什么建议么?
基本 R 解决方案(在您的示例数据中,您目前没有匹配项):
test1$dat.citystate <- with(test2, citystate[match(test1$zip, zip)])
数据:
test1 <- structure(list(zip = c(80914L, 32920L, 80914L, 80914L, 80914L,
80914L), dat.citystate = c("Moody, AL", NA, "Moody, AL", "Moody, AL",
"Moody, AL", "Moody, AL")), row.names = c(NA, -6L), class = "data.frame")
test2 <- structure(list(`zip citystate` = c("80914 Moody, AL", "35005 Adamsville, AL",
"35006 Adger, AL", "35007 Alabaster, AL", "35010 Alexander City, AL",
"35011 Alexander City, AL"), zip = c(80914, 35005, 35006, 35007,
35010, 35011), citystate = c("Moody, AL", "Adamsville, AL", "Adger, AL",
"Alabaster, AL", "Alexander City, AL", "Alexander City, AL")), row.names = c(NA,
-6L), class = "data.frame")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.