XML数据框列表

时间:2014-11-25 16:01:56

标签: xml r dataframe

我有以下数据框:

tests <- c("test1", "test1", "test1")
obs <- c("observation1", "observation2", "observation3")

test <- data.frame(tests, obs, stringsAsFactors = FALSE)

我想将其转换为具有特定格式的XML文件:

library(XML)

example <- newXMLNode("example")
addAttributes(example, name=test$tests[1])
observations <- lapply(seq_along(test$obs),function(x){newXMLNode("obs",
                attrs = c(ID = paste(test$tests[1], "-", as.character(x), sep="")),
                .children = test$obs[x])
})
addChildren(example, observations)

saveXML(example, file=paste0(test$tests[1], ".xml"))

这会将名为test1.xml的项目保存到我的工作目录:

<example name="test1">
  <obs ID="test1-1">observation1</obs>
  <obs ID="test1-2">observation2</obs>
  <obs ID="test1-3">observation3</obs>
</example> 

但是如果我在一个数据帧中有一个数据帧列表呢?像这样:

tests <- c("test1", "test1", "test1", "test2", "test2", "test2", "test3", "test3")
obs <- c("observation1", "observation2", "observation3", "observation4", "observation5", "observation6", "observation7", "observation8")
test <- data.frame(tests, obs, stringsAsFactors = FALSE)
test <- split(test, test$tests)

我想将它们保存为自己的XML文件,现在作为test1.xml,test2.xml,test3.xml,但上面的代码不起作用,我没有修复它。我知道我应该以某种方式遍历每个列表项。

1 个答案:

答案 0 :(得分:1)

Richard Scriven是对的。以下是执行此操作的代码:

dfToXML <- function(test) {
    example <- newXMLNode("example")
    addAttributes(example, name=test$tests[1])
    observations <- lapply(seq_along(test$obs),function(x){newXMLNode("obs",
                    attrs = c(ID = paste(test$tests[1], "-", as.character(x), sep="")),
                    .children = test$obs[x])
    })
    addChildren(example, observations)
    saveXML(example, file=paste0(test$tests[1], ".xml"))
}
lapply(test, dfToXML)