I have some data shaped like this:
<people>
<person first="Mary" last="Jane" sex="F" />
<person first="Susan" last="Smith" sex="F" height="168" />
<person last="Black" first="Joseph" sex="M" />
<person first="Jessica" last="Jones" sex="F" />
</people>
I would like a data frame that looks like this:
first last sex height
1 Mary Jane F NA
2 Susan Smith F 168
3 Joseph Black M NA
4 Jessica Jones F NA
I've gotten this far:
library(XML)
xpeople <- xmlRoot(xmlParse(xml))
lst <- xmlApply(xpeople, xmlAttrs)
names(lst) <- 1:length(lst)
But I can't for the life of me figure out how to get the list into the data frame. I can get the list to be "square" (i.e. fill in the gaps) and then put it into a data frame:
lst <- xmlApply(xpeople, function(node) {
attrs = xmlAttrs(node)
if (!("height" %in% names(attrs))) {
attrs[["height"]] <- NA
}
attrs
})
df = as.data.frame(lst)
But I have the following problems:
How can I get the data frame in the correct form?
txt <- '<people>
<person first="Mary" last="Jane" sex="F" />
<person first="Susan" last="Smith" sex="F" height="168" />
<person last="Black" first="Joseph" sex="M" />
<person first="Jessica" last="Jones" sex="F" />
</people>'
library(XML) # for xmlTreeParse
library(data.table) # for rbindlist(...)
xml <- xmlTreeParse(txt, asText=TRUE, useInternalNodes = TRUE)
rbindlist(lapply(xml["//person"],function(x)as.list(xmlAttrs(x))),fill=TRUE)
# first last sex height
# 1: Mary Jane F NA
# 2: Susan Smith F 168
# 3: Joseph Black M NA
# 4: Jessica Jones F NA
You need as.list(xmlAttrs(...))
instead of just xmlAttrs(...)
because rbindlist(...)
wants each argument to be a list, not a vector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With