0

私はウェブサイトhttp://www.crowdrise.com/CDISkollで作業しています

私が作成した次の R コードを検討してください。

library("RCurl")
library("XML")
library("stringr")

user.address<-"http://www.crowdrise.com/CDISkoll"                     
user.url<-getURL(user.address)       
html <- htmlTreeParse(user.url, useInternalNodes = TRUE)

if(!is.null(xpathSApply(html,
   '//div[@class="grid1-4"]//p[@class="progressText"]',xmlValue))){
       website.goal.percentage<-
               do.call("paste",as.list(xpathSApply(html,
                '//div[@class="grid1-4"]//p[@class="progressText"]',xmlValue)))
} 

if(is.null(xpathSApply(html,
  '//div[@class="grid1-4"]//p[@class="progressText"]',xmlValue))){
          website.goal.percentage<-"Not Available"
}

上記のWebサイトには、 xpath に関する情報は含まれていません //div[@class="grid1-4"]//p[@class="progressText"]。したがって、私の変数website.goal.percentageは文字列でなければなりません"Not Available"。しかし、R でコードを実行すると、...website.goal.percentage が返されます。character(0)

R"Not Available"が変数website.goal.percentageに格納されないのはなぜですか?どうすれば修正できますか?

4

1 に答える 1

1

これは非常に簡単に診断できます。xpathSApplyここで空のリストが返され、R がそれをどのように判断するかがわかりis.null(list())ますFALSE。代わりに、それをチェックする必要がありますlength(...) == 0

xpathApplyリストを体系的に返すため、使用することもお勧めします。最後に、変数を使用すると、コードがどのように見栄えがよくなるかを確認してください。

nodes <- xpathApply(html, '//div[@class="grid1-4"]//p[@class="progressText"]',
                    xmlValue)

website.goal.percentage <- if(length(nodes) == 0) "Not Available" else
                           do.call("paste", nodes)
于 2013-10-19T21:56:04.237 に答える