[英]How to create a dataframe in R from xml, keep getting error cannot coerce class "xml_nodeset" to a data.frame
我正在嘗試從 XML 中提取屬性,但是當我嘗試將它們放入 dataframe 時,我不斷收到錯誤。 我想使用“windDirection”和“windSpeed”數據,並擁有與風向和風速測量相對應的“從”和“到”時間和日期戳。
library(xml2)
as_list(wind_data <- read_xml("https://metwdb-openaccess.ichec.ie/metno-wdb2ts/locationforecast?lat=51.6547167;long=-9.7734153"))
# Wind direction
direction <- wind_data %>% xml_find_all("//windDirection")
direction %>% xml_attr("deg") %>% as.numeric()
# Wind speed
speed <- wind_data %>% xml_find_all("//windSpeed")
speed %>% xml_attr("mps") %>% as.numeric()
# to and from
time <- wind_data %>% xml_find_all("//time")
time %>% xml_attr("from") %>% as.character()
time %>% xml_attr("to") %>% as.character()
wind_data <- data.frame(direction, speed, time)
我也試過:
library(XML)
wind_data <- xmlToDataFrame(time, direction, speed)
但我收到以下錯誤:
(函數(類,fdef,mtable)中的錯誤:無法為簽名“xml_nodeset”、“xml_nodeset”、“xml_nodeset”、“missing”、“missing”找到 function 'xmlToDataFrame' 的繼承方法
我對使用 XML 格式非常陌生,所以我很容易在這里遺漏一些非常簡單的東西,但我似乎找不到答案。 任何幫助或指示將不勝感激。
問題是轉換后的結果沒有存儲在新變量中。
還查看 xml 文件,由於每個預測有兩個時間節點,因此需要將時間值的數量減少一半。
library(xml2)
as_list(wind_data <- read_xml("https://metwdb-openaccess.ichec.ie/metno-wdb2ts/locationforecast?lat=51.6547167;long=-9.7734153"))
# Wind direction and update data
direction <- wind_data %>% xml_find_all("//windDirection")
direction <- direction %>% xml_attr("deg") %>% as.numeric()
# Wind speed and update data
speed <- wind_data %>% xml_find_all("//windSpeed")
speed <-speed %>% xml_attr("mps") %>% as.numeric()
# to and from
time <- wind_data %>% xml_find_all("//time")
#there are 2 time for each speed and direction
timereduced <- time[ as.logical((1:length(time))%%2) ]
from <- timereduced %>% xml_attr("from")
to <- timereduced %>% xml_attr("to")
results <- data.frame(direction, speed, from, to)
根據 Parfait 的建議:
timenodes <- wind_data %>% xml_find_all(".//time[not(location/precipitation)]")
from <- timenodes %>% xml_attr("from")
to <- timenodes %>% xml_attr("to")
direction <- timenodes %>% xml_find_all("//windDirection") %>% xml_attr("deg") %>% as.numeric()
speed <- timenodes %>% xml_find_first(".//windSpeed") %>% xml_attr("mps") %>% as.numeric()
results <- data.frame(direction, speed, from, to)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.