我正在尝试从Zillow API读取信息并在R中遇到一些数据结构问题.我的输出应该是xml并且看起来像是,但是不像xml那样. 具体来说,GetSearchResults()返回给我的对象采用类似于XML的格式,但在R的
具体来说,GetSearchResults()返回给我的对象采用类似于XML的格式,但在R的XML读取函数中读取不太正确.
你能告诉我怎么办吗?
#set directory setwd('[YOUR DIRECTORY]') # setup libraries library(dplyr) library(XML) library(ZillowR) library(RCurl) # setup api key set_zillow_web_service_id('[YOUR API KEY]') xml = GetSearchResults(address = '120 East 7th Street', citystatezip = '10009') data = xmlParse(xml)
这会引发以下错误:
Error: XML content does not seem to be XML
Zillow API文档明确指出输出应该是XML,它看起来确实如此.我希望能够轻松访问API输出的各种组件,以进行更大规模的数据操作/聚合.如果您有任何想法,请告诉我.
这对我来说是一个有趣的机会,可以熟悉Zillow API.在 How to parse XML to R data frame之后,我的方法是将响应转换为列表,以便于检查.繁琐的一点是通过检查列表来确定数据的结构,特别是因为每个属性可能都有一些丢失的数据.这就是我编写getValRange函数来处理解析Zestimate数据的原因.results <- xmlToList(xml$response[["results"]]) getValRange <- function(x, hilo) { ifelse(hilo %in% unlist(dimnames(x)), x["text",hilo][[1]], NA) } out <- apply(results, MAR=2, function(property) { zpid <- property$zpid links <- unlist(property$links) address <- unlist(property$address) z <- property$zestimate zestdf <- list( amount=ifelse("text" %in% names(z$amount), z$amount$text, NA), lastupdated=z$"last-updated", valueChange=ifelse(length(z$valueChange)==0, NA, z$valueChange), valueLow=getValRange(z$valuationRange, "low"), valueHigh=getValRange(z$valuationRange, "high"), percentile=z$percentile) list(id=zpid, links, address, zestdf) }) data <- as.data.frame(do.call(rbind, lapply(out, unlist)), row.names=seq_len(length(out)))
样本输出:
> data[,c("id", "street", "zipcode", "amount")] id street zipcode amount 1 2098001736 120 E 7th St APT 5A 10009 2321224 2 2101731413 120 E 7th St APT 1B 10009 2548390 3 2131798322 120 E 7th St APT 5B 10009 2408860 4 2126480070 120 E 7th St APT 1A 10009 2643454 5 2125360245 120 E 7th St APT 2A 10009 1257602 6 2118428451 120 E 7th St APT 4A 10009 <NA> 7 2125491284 120 E 7th St FRNT 1 10009 <NA> 8 2126626856 120 E 7th St APT 2B 10009 2520587 9 2131542942 120 E 7th St APT 4B 10009 1257676