[英]R using getURL data to dataframe
我正在从Web下载数据,但是不知道如何将其更改为数据框或任何有用的东西。 有没有人有什么建议? 这是代码:
library(RCurl)
myfile = getURL(http://www.stat.ufl.edu/~winner/data/lister_ul.dat,
ssl.verifyhost=FALSE, ssl.verifypeer=FALSE)
如果我使用这个:
A = read.csv(textConnection(myfile), header = F)
然后R明白这一点:
c("1 1 1")
作为第一行,而不是:
c(1, 1, 1).
这不起作用b / c我需要使用
colnames(A) = c("col1", "col2", "col3")
并且找不到不涉及使用以下乏味工作的变通办法
unlist(strsplit(A))
gh!
任何建议,将不胜感激。 或者,如有必要,我可能会编写自己的乏味函数。
格温
这有帮助吗?
df <- read.table('http://www.stat.ufl.edu/~winner/data/lister_ul.dat')
你近了 由于我没有安装RCurl
但是我确实有httr
(使用curl
),因此我将httr
开始。 但是,这是一个有争议的问题,因为我得到的内容与您相同。
另外,@ udden2903的答案更加简单明了,我假设这是一个简化的问题,并且您可能需要继续使用read.table(URL)
不允许的替代获取方法。 (要继续使用httr
并支持其他一些功能,例如身份验证,请阅读其文档。)
library(httr)
myfile = GET("http://www.stat.ufl.edu/~winner/data/lister_ul.dat")
str(content(myfile))
# No encoding supplied: defaulting to UTF-8.
# chr "1 1 1\n1 0 11\n0 1 6\n0 0 6\n"
因此, content(myfile)
现在就是您的myfile
。 第一个技巧是您的数据不是逗号分隔的(“ csv”),因此必须使用read.table
。 其次,您需要指定第一行不是标题。
x <- read.table(textConnection(content(myfile, encoding = "UTF-8")), header = FALSE)
x
# V1 V2 V3
# 1 1 1 1
# 2 1 0 11
# 3 0 1 6
# 4 0 0 6
现在,只需分配标题即可。
colnames(x) <- c("col1", "col2", "col3")
x
# col1 col2 col3
# 1 1 1 1
# 2 1 0 11
# 3 0 1 6
# 4 0 0 6
as.data.frame(
do.call("rbind", strsplit(
readLines("http://www.stat.ufl.edu/~winner/data/lister_ul.dat"),
"\\s+"))
)
V1 V2 V3
1 1 1 1
2 1 0 11
3 0 1 6
4 0 0 6
我们要做的是从网页中读取原始行,然后用返回的字符之间的空格分隔每一行,然后通过在每一行上调用rbind
创建一个矩阵...然后将其转换为数据框。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.