我試圖通過訪問Web服務和搜索郵政編碼來建立一個巴西地址的數據框。實際上,我可以接收一個單獨的結果並將其存儲在一個數據框中,但是當我嘗試搜索多個郵政編碼(例如向量中)時,我的數據框只保留最後一個元素。 有人可以幫我嗎?R.如何將循環(for)結果追加到數據框中?
請參見下面的代碼:
###############
library(httr)
library(RCurl)
library(XML)
library(dplyr)
###############
# ZIPs I want to search for:
vectorzip <- c("71938360", "70673052", "71020510")
j <- length(vectorzip)
# loop:
for(i in 1:j) {
# Save the URL of the xml file in a variable:
xml.url <- getURL(paste("http://cep.republicavirtual.com.br/web_cep.php?cep=",vectorzip[i], sep = ""), encoding = "ISO-8859-1")
xml.url
# Use the xmlTreeParse-function to parse xml file directly from the web:
xmlfile <- xmlTreeParse(xml.url)
xmlfile
# the xml file is now saved as an object you can easily work with in R:
class(xmlfile)
# Use the xmlRoot-function to access the top node:
xmltop = xmlRoot(xmlfile)
# have a look at the XML-code of the first subnodes:
print(xmltop)
# To extract the XML-values from the document, use xmlSApply:
zips <- xmlSApply(xmlfile, function(x) xmlSApply(x, xmlValue))
zips
# Finally, get the data in a data-frame and have a look at the first rows and columns:
zips <- NULL
zips <- rbind(zips_df, data.frame(t(zips),row.names=NULL))
View(zips_df)}
什麼是zips < - NULL行爲zips_df定義的位置? –
用rbind生長一個對象通常不是一個好主意。更好的方法是定義一個特定大小的空數據框(從而分配必要的內存),然後填充行。 – RHertel