1
我不知道在R
中使用xpathSApply
時是否有使用條件語句的選項。下面的例子工作正常,但我想有更有效的選擇?R xpathApply:如何在使用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
那麼,有沒有使用條件語句代替這個循環的選項?