【问题标题】:Reading text file with read.fwf使用 read.fwf 读取文本文件
【发布时间】:2016-02-16 11:23:32
【问题描述】:

当我尝试在 R 中读取文本文件时出现错误:

“扫描错误(文件,内容,nmax,sep,dec,引用,skip,nlines,na.strings,: 第 2 行没有 5 个元素”

我尝试使用以下代码读取文本文件:

read.fwf(file=url("http://d396qusza40orc.cloudfront.net/getdata%2Fwksst8110.for"),
         widths=c(9,8, 8, 8, 8),sep = "", skip = 2, header= TRUE)

我加载了包readr

【问题讨论】:

  • 您需要跳过 3 行,因为您有 2 行标题。之后就可以修改header了。
  • @Pascal 感谢您的建议,但是,它并没有解决问题。使用不同的行号时,我遇到了同样的错误。

标签: r


【解决方案1】:

你写的是你正在使用包readr,但是你使用base函数来读取一个固定宽度的文件。

加载 readr 后,您可以使用以下内容加载数据。正如 Pascal 提到的那样,跳过前 3 行,如果您指定 col_names = FALSE,则跳过 4 行(参见代码)。也不需要指定固定宽度,因为它是一个很好的表格格式,由空格分隔。函数 read_table 应该可以正常工作。

library(readr)

file <- "http://d396qusza40orc.cloudfront.net/getdata%2Fwksst8110.for"
df2 <- read_table(file, skip = 4, col_names = FALSE)

# Check information in file and check how the headers should be
read_lines(file, n_max = 4)

[1] " Weekly SST data starts week centered on 3Jan1990"              ""                                                              
[3] "                Nino1+2      Nino3        Nino34        Nino4"  " Week          SST SSTA     SST SSTA     SST SSTA     SST SSTA"

# Set correct header names. Manually was faster than programming.
names(df2) <- c("Week", "Nino1+2 SST SSTA", "Nino3 SST SSTA", "Nino34 SST SSTA", "Nino4 SST SSTA") 
head(df2)

       Week Nino1+2 SST SSTA Nino3 SST SSTA Nino34 SST SSTA Nino4 SST SSTA
1 03JAN1990         23.4-0.4       25.1-0.3        26.6 0.0       28.6 0.3
2 10JAN1990         23.4-0.8       25.2-0.3        26.6 0.1       28.6 0.3
3 17JAN1990         24.2-0.3       25.3-0.3        26.5-0.1       28.6 0.3
4 24JAN1990         24.4-0.5       25.5-0.4        26.5-0.1       28.4 0.2
5 31JAN1990         25.1-0.2       25.8-0.2        26.7 0.1       28.4 0.2
6 07FEB1990         25.8 0.2       26.1-0.1        26.8 0.1       28.4 0.3 

【讨论】:

    猜你喜欢
    • 2020-04-19
    • 2010-11-27
    • 2012-05-26
    • 2012-09-04
    • 2016-04-17
    • 2013-04-12
    • 2020-03-21
    • 2020-12-24
    • 2016-12-01
    相关资源
    最近更新 更多