r语言 - data.table 的 fread() 可以跳过第二个空行并保留第一行标题吗?



我试图读取一个CSV,其中列标题在第1行,但第2行为空,数据从第3行开始。我尝试了下面的各种选项,但最终总是使用通用的V#列名。关于如何保留列标题,有什么想法吗?

fread("https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv",
header = F)
fread("https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv",
skip = 0)
fread("https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv",
skip = 1)
fread("https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv",
blank.lines.skip = T)
fread("https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv",
skip = 0, blank.lines.skip = T)
fread("https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv",
header = F, skip = 0, blank.lines.skip = T)
url ="https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv"
df = fread(url,header=F)
headers = names(fread(url, nrows=0))
setnames(df, old=1:length(headers), new = headers)

我注意到有20个标题,但返回了22列。因此,我用标题中的20个名称命名了前20列。

正如r2evans在评论中所建议的那样,为了避免双重下载/阅读,你可以这样做:

url ="https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv"
# download file
tfile = tempfile()
curl::curl_download(url,destfile = tfile)
# read to get headers
headers = names(fread(tfile, nrows=0))
# read to get data
df = fread(tfile, header=F)
# set the names based on `headers`
setnames(df, old=1:length(headers), new = headers)
# remove the file
file.remove(tfile)

最新更新