RCurl或XML Challenge:将Pastebin读入R中

时间:2011-05-22 07:00:38

标签: r

灵活训练你的RCurl / XML肌肉。最短的代码获胜。解析为R:http://pastebin.com/CDzYXNbG

数据应该是:

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

4 个答案:

答案 0 :(得分:5)

和kohske一样的想法,但我认为会更短更清晰

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

答案 1 :(得分: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 Long的优秀解决方案之后,这是一个最短的代码:

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

答案 2 :(得分: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=""))))

仍然让我处于领先地位:)。

答案 3 :(得分: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)

我也很确定这可以在某种程度上得到改善,但它确实可以完成我认为你要求的工作。即使没有:感谢让我想要刷新我的正则表达式基础知识!