I have a following data frame:
tests <- c("test1", "test1", "test1")
obs <- c("observation1", "observation2", "observation3")
test <- data.frame(tests, obs, stringsAsFactors = FALSE)
I want to turn that into an XML file with specific formatting:
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"))
This saves to my working directory this item with name test1.xml:
<example name="test1">
<obs ID="test1-1">observation1</obs>
<obs ID="test1-2">observation2</obs>
<obs ID="test1-3">observation3</obs>
</example>
But what if I have instead a single data frame a list of data frames? Like this:
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)
I want to save each of them as their own XML file, now as test1.xml, test2.xml, test3.xml, but the code above doesn't work and I'm not getting it fixed. I understand I should somehow loop through each list item.
No comments:
Post a Comment