【问题标题】:rbind txt files from online directory (R)rbind 来自在线目录的 txt 文件 (R)
【发布时间】:2017-02-11 21:00:57
【问题描述】:

我正在尝试从 url 获取连接文本文件,但我不知道如何使用 html 和不同的文件夹执行此操作?

这是我试过的代码,但它只列出了文本文件并且有很多像this这样的html代码我该如何解决这个问题,以便我可以将文本文件合并到一个csv文件中?

library(RCurl)
url <- "http://weather.ggy.uga.edu/data/daily/"
dir <- getURL(url, dirlistonly = T)
filenames <- unlist(strsplit(dir,"\n")) #split into filenames
#append the files one after another
for (i in 1:length(filenames)) {
file <- past(url,filenames[i],delim='') #concatenate for urly 
if (i==1){
cp <- read_delim(file, header=F, delim=',')
}
else{
temp <- read_delim(file,header=F,delim=',')
cp <- rbind(cp,temp) #append to existing file
rm(temp)# remove the temporary file
}
}

【问题讨论】:

    标签: r concatenation rbind stringr


    【解决方案1】:

    这是我必须为我工作的代码 sn-p。我喜欢在 RCurl 上使用 rvest,因为这是我学到的。在这种情况下,我可以使用html_nodes 函数来隔离每个以.txt 结尾的文件。结果表将时间保存为字符串,但您可以稍后修复它。如果您有任何问题,请告诉我。

    library(rvest)
    library(readr)
    
    url <- "http://weather.ggy.uga.edu/data/daily/"
    
    doc <- xml2::read_html(url)
    text <- rvest::html_text(rvest::html_nodes(doc, "tr td a:contains('.txt')"))
    
    
    # define column types of fwf data ("c" = character, "n" = number)
    ctypes <- paste0("c", paste0(rep("n",11), collapse = ""))
    data <- data.frame()
    
    for (i in 1:2){
      file <- paste0(url, text[1])
    
      date <- as.Date(read_lines(file, n_max = 1), "%m/%d/%y")
    
      # Read file to determine widths
      columns <- fwf_empty(file, skip = 3)
    
      # Manually expand `solar` column to be 3 spaces wider
      columns$begin[8] <- columns$begin[8] - 3
    
      data <- rbind(data, cbind(date,read_fwf(file, columns, 
                                              skip = 3, col_types = ctypes)))
    }
    

    【讨论】:

    • 非常感谢您的帮助!
    • 您好,由于某种原因,第 9 列(太阳能)没有正确的值。它只有最后一个数字。这是它影响的唯一列。有没有办法解决这个问题?
    • 这似乎是fwf_empty 的问题,这是一个确定列结束和开始的函数。我创建了一个不理想但应该适合您的手动修复。
    猜你喜欢
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    相关资源
    最近更新 更多