2011-05-22 71 views
6

Flex您的RCurl/XML肌肉。最短的代碼獲勝。解析爲R:http://pastebin.com/CDzYXNbGRCurl或XML挑戰:將Pastebin讀入R

數據應該是:

structure(list(Treatment = structure(c(2L, 2L, 1L, 1L), .Label = c("C", 
"T"), class = "factor"), Gender = c("M", "F", "M", "F"), Response = c(56L, 
58L, 6L, 63L)), .Names = c("Treatment", "Gender", "Response"), row.names = c(NA, 
-4L), class = "data.frame") 

祝你好運!

注意:此問題友好地提供虛擬數據:Adding space between bars in ggplot2

回答

5

相同的思路kohske但略短,更清楚,我想

library(XML) 
eval(parse(text=gsub('\r\n','\n',xpathApply(htmlTreeParse('http://pastebin.com/CDzYXNbG',useInternal=T),'//textarea',xmlValue)))) 
+0

到目前爲止,看起來像喲因爲這樣可以在沒有其他字符的情況下插入數據幀,並且可以輕鬆地分配給變量,因此您處於領先地位。 – 2011-05-22 17:49:26

+0

+1代碼的剪切清晰度。而且沒有作弊! – 2011-05-23 02:50:56

+0

選擇使用指定頁面的最短代碼。 Congratz! – 2011-05-25 12:03:41

1

我不完全相信你正試圖在這裏實現什麼,但也許你不要求什麼(不使用任何花哨的包裝,只是正則表達式) :

fullText<-(paste(readLines("http://pastebin.com/CDzYXNbG"), collapse="\n")) 
regexp<-"<textarea[^>]*id=\"paste_code\"[^>]*>(.*)</textarea>" 
txtarpos<-regexpr(regexp, fullText) 
txtarstrt<-txtarpos[1] 
txtarlen<-unlist(attributes(txtarpos)["match.length"]) 
txtarstp<-txtarstrt+txtarlen 
txtarpart<-substr(fullText, txtarpos[1], txtarstp) 
retval<-gsub("\n", "", gsub("&quot;", "\"", gsub(regexp, "\\1", txtarpart), fixed=TRUE), fixed=TRUE) 
cat(retval) 

我也非常肯定這可以在一定程度上得到改善,但它確實做了我認爲你所要求的工作。即使不:謝謝讓我想刷新我的正則表達式的基礎知識!

+0

'錯誤:意外輸入 「RETVAL <-gsub(」 \ n」 ,「」,gsub(「"」,「\」「,gsub(regexp,」\\ 1「,txtarpart),fixed = TRUE),fixed = TRUE)」有趣的使用純正規表達式 – 2011-05-22 17:53:31

4

對於我的代碼,RCurl不是必需的,因爲XML包可以解析文件參數的URL。

請執行

library(XML) 
下面的例子前

代碼1 oneliner

eval(parse(text=htmlTreeParse("http://pastebin.com/CDzYXNbG",handlers=(function(){qt <- NULL;list(textarea=function(node,...){qt<<-gsub("[\r\n]", "", unclass(node$children$text)$value);node},.qt=function()qt)})())$.qt())) 

代碼2短,但我覺得這不是最短的。

htmlTreeParse("http://pastebin.com/CDzYXNbG",h=list(textarea=function(n)z<<-gsub("[\r\n]","",unclass(n$c$t)$v)));eval(parse(text=z)) 

由於這個問題是一種遊戲,請解密此代碼。



修訂

看着@JD龍的優秀的解決方案後,這裏是一個最短代碼:

eval(parse(file(sub("m/","m/raw.php?i=","http://pastebin.com/CDzYXNbG")))) 

現在的問題是如何在最短的代碼所需的URL字符串;-p

再次更新。這是由一些字符縮短。

source(sub("m/","m/raw.php?i=","http://pastebin.com/CDzYXNbG"))$va 
+0

Code 1 works代碼2不能分配給一個變量,雖然很好,但試試! – 2011-05-22 17:52:22

+0

您可以在代碼2中進行分配。請仔細查看代碼。 – kohske 2011-05-22 23:35:35

+0

技術上最短,但不使用指定的頁面。 – 2011-05-25 12:02:03

4

你們正在這樣太難:

eval(parse(file("http://pastebin.com/raw.php?i=CDzYXNbG")))

好了,我被騙了。但是從同一個URL開始,你可以得到同樣的目的:

eval(parse(file(paste("http://pastebin.com/raw.php?i=", strsplit("http://pastebin.com/CDzYXNbG", "/")[[1]][4], sep=""))))

仍然使我處於領先:)

+0

+1我喜歡這類解決方案。 – kohske 2011-05-22 23:41:13

+0

+1爲創意品牌' – 2011-05-23 02:52:35

+0

我喜歡第一個;) – 2011-05-23 03:11:45