R xpathApply:使用xpathSApply时如何使用条件语句而不是循环?

R xpathApply: how to use conditional statement instead of looping when using xpathSApply?

我想知道在R中使用xpathSApply时是否有使用条件语句的选项。下面的示例工作正常,但我想还有更有效的选择吗?

exemel<-'<?xml version="1.0" encoding="utf-8"?>
<Production  xmlns="http://www.w3.org/2001/XMLSchema-instance">
    <Item>
        <ItemNr>1</ItemNr>
        <Category>Processing</Category>
        <Processed>
            <Dia>325</Dia>
            <Log>
                <LogKey>1</LogKey>
            </Log>
            <Log>
                <LogKey>2</LogKey>
            </Log>
        </Processed>
    </Item>
    <Item>
        <ItemNr>2</ItemNr>
        <Category>NoProcessing</Category>
        <NotProcessed>
            <Dia>72</Dia>
        </NotProcessed>
    </Item>
    <Item>
        <ItemNr>3</ItemNr>
        <Category>Processing</Category>
        <Processed>
            <Dia>95</Dia>
            <Log>
                <LogKey>1</LogKey>
            </Log>
        </Processed>
    </Item>
</Production>'

xmlf <- xmlParse(exemel)
nsDefs <- xmlNamespaceDefinitions(xmlf, simplify=T)
ItemNumbers <- as.numeric(xpathSApply(xmlf, "//d:Item/d:ItemNr", xmlValue, namespaces=c(d=nsDefs[[1]])))

maxkeys=NULL
for (i in ItemNumbers) {  
  logkeys <- as.numeric(xpathSApply(xmlf, paste("//d:Item[d:ItemNr='", i, "']//d:LogKey", sep=""), 
                                    xmlValue, namespaces=c(d=nsDefs[[1]])))
  if (length(logkeys)>0) {
    maxkeys[i] = max(logkeys)
  } else {
    maxkeys[i]  = NA
  }  
}   
print(maxkeys)
#[1] 2 NA 1

那么,是否有任何选项可以使用条件语句来代替此循环?

定义 getMaxLogKey 以获取最大 LogKey 给定的 Item 节点,然后将其应用于所有项目:

library(XML)
xmlf <- xmlParse(exemel)

getMaxLogKey <- function(x) {
  LogKeys <- xpathSApply(x, ".//d:LogKey", xmlValue, namespaces = "d")
  if (length(LogKeys)) max(as.numeric(LogKeys)) else NA
}

xpathSApply(xmlf, "//d:Item", getMaxLogKey, namespaces = "d")

给予:

[1]  2 NA  1