当我试图读取R中的文本文件时,会遇到一个错误:
扫描错误(文件,什么,nmax,9月,12月,引号,跳过,nline,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。
发布于 2015-11-15 09:08:47
您写到您正在使用package,但是您使用基函数读取一个固定宽度的文件。
加载了readr之后,您可以使用以下方法加载数据。正如Pascal所提到的,如果您指定col_names = FALSE (参见代码),则跳过前3行。此外,也不需要指定固定的宽度,因为它是一种很好的表格式,由空格分割。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 https://stackoverflow.com/questions/33717138
复制相似问题