programing

XML 파일을 R 데이터 프레임으로 구문 분석하는 방법은 무엇입니까?

jooyons 2023. 6. 9. 22:00
반응형

XML 파일을 R 데이터 프레임으로 구문 분석하는 방법은 무엇입니까?

XML 파일을 R 데이터 프레임에 구문 분석하려고 했습니다.이 링크는 저에게 많은 도움이 되었습니다.

xml 파일에서 R 데이터 프레임을 만드는 방법은 무엇입니까?

하지만 여전히 저는 제 문제를 이해할 수 없었습니다.내 코드는 다음과 같습니다.

data <- xmlParse("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")
xmlToDataFrame(nodes=getNodeSet(data1,"//data"))[c("location","time-layout")]
step1 <- xmlToDataFrame(nodes=getNodeSet(data1,"//location/point"))[c("latitude","longitude")]
step2 <- xmlToDataFrame(nodes=getNodeSet(data1,"//time-layout/start-valid-time"))
step3 <- xmlToDataFrame(nodes=getNodeSet(data1,"//parameters/temperature"))[c("type="hourly"")]

제가 원하는 데이터 프레임은 다음과 같습니다.

latitude  longitude   start-valid-time   hourly_temperature
29.803     -82.411  2013-06-19T15:00:00-04:00    91
29.803     -82.411  2013-06-19T16:00:00-04:00    90

저는 꼼짝 못하고 있습니다.xmlToDataFrame()어떤 도움이라도 주시면 대단히 감사하겠습니다.

XML 형식의 데이터는 거의 구성되지 않습니다.xmlToDataFrame기능을 발휘합니다.목록의 모든 항목을 추출한 다음 데이터 프레임에서 목록을 함께 바인딩하는 것이 좋습니다.

require(XML)
data <- xmlParse("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")

xml_data <- xmlToList(data)

예제 데이터의 경우 위치와 시작 시간을 얻는 것은 매우 간단합니다.

location <- as.list(xml_data[["data"]][["location"]][["point"]])

start_time <- unlist(xml_data[["data"]][["time-layout"]][
    names(xml_data[["data"]][["time-layout"]]) == "start-valid-time"])

온도 데이터는 좀 더 복잡합니다.먼저 온도 목록이 포함된 노드로 이동해야 합니다.그런 다음 두 개의 목록을 추출하고 각 목록 내에서 확인한 다음 "시간별"이 있는 목록을 값 중 하나로 선택해야 합니다.그런 다음 해당 목록만 선택하고 "값" 레이블이 있는 값만 유지해야 합니다.

temps <- xml_data[["data"]][["parameters"]]
temps <- temps[names(temps) == "temperature"]
temps <- temps[sapply(temps, function(x) any(unlist(x) == "hourly"))]
temps <- unlist(temps[[1]][sapply(temps, names) == "value"])

out <- data.frame(
  as.list(location),
  "start_valid_time" = start_time,
  "hourly_temperature" = temps)

head(out)
  latitude longitude          start_valid_time hourly_temperature
1    29.81    -82.42 2013-06-19T16:00:00-04:00                 91
2    29.81    -82.42 2013-06-19T17:00:00-04:00                 90
3    29.81    -82.42 2013-06-19T18:00:00-04:00                 89
4    29.81    -82.42 2013-06-19T19:00:00-04:00                 85
5    29.81    -82.42 2013-06-19T20:00:00-04:00                 83
6    29.81    -82.42 2013-06-19T21:00:00-04:00                 80

성능과 명확성 모두를 위해 xpath를 보다 직접적으로 사용합니다.

time_path <- "//start-valid-time"
temp_path <- "//temperature[@type='hourly']/value"

df <- data.frame(
    latitude=data[["number(//point/@latitude)"]],
    longitude=data[["number(//point/@longitude)"]],
    start_valid_time=sapply(data[time_path], xmlValue),
    hourly_temperature=as.integer(sapply(data[temp_path], as, "integer"))

로 이어지는.

> head(df, 2)
  latitude longitude          start_valid_time hourly_temperature
1    29.81    -82.42 2014-02-14T18:00:00-05:00                 60
2    29.81    -82.42 2014-02-14T19:00:00-05:00                 55

다음은 xml2를 사용한 부분 솔루션입니다.일반적으로 솔루션을 더 작은 조각으로 분할하면 모든 것이 정렬되도록 하는 것이 더 쉬워집니다.

library(xml2)
data <- read_xml("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")

# Point locations
point <- data %>% xml_find_all("//point")
point %>% xml_attr("latitude") %>% as.numeric()
point %>% xml_attr("longitude") %>% as.numeric()

# Start time
data %>% 
  xml_find_all("//start-valid-time") %>% 
  xml_text()

# Temperature
data %>% 
  xml_find_all("//temperature[@type='hourly']/value") %>% 
  xml_text() %>% 
  as.integer()

아래 코드를 사용해 보십시오.

# Load the packages required to read XML files.
library("XML")
library("methods")

# Convert the input xml file to a data frame.
xmldataframe <- xmlToDataFrame("input.xml")
print(xmldataframe)

언급URL : https://stackoverflow.com/questions/17198658/how-to-parse-an-xml-file-to-an-r-data-frame

반응형