2015-03-13 40 views
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 

那麼,有沒有使用條件語句代替這個循環的選項?

回答

0

定義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