将.csv文件加载到RStudio时出现问题。用引号引起来的EOF字符串

时间:2018-12-09 18:10:10

标签: r csv import dataset

当我将此文件Chicago_Crimes_2005_to_2007.csv(链接https://www.kaggle.com/currie32/crimes-in-chicago)加载到RStudio中时,总是收到错误消息(警告: 在scan(file = file,what = what,sep = sep,quote = quote,dec = dec ,: Zeichenkette中的EOF /英语:带有引号的字符串中的EOF)中,并且没有包括所有的内容。你知道如何解决这个问题吗?使用其他3个文件,我没有任何问题。我正在使用此代码:

c2 = read.csv("Chicago_Crimes_2005_to_2007.csv", header = TRUE)

我尝试使用以下代码对其进行修复:

c2 = read.csv("Chicago_Crimes_2005_to_2007.csv", header = TRUE, quote = "", row.names = NULL, stringsAsFactors = FALSE). 

努力锻炼。我在这里用相同的错误在stackoverflow中尝试了所有答案。没有任何帮助。自1周以来没有成功。希望有人能帮助我。在RStudio中使用R。

2 个答案:

答案 0 :(得分:0)

您在这里:

require(tidyverse)
df <- readr::read_csv("Chicago_Crimes_2005_to_2007.csv")

您可以决定清除列名,因为有些列中有空格:

colnames(df) <- c("rowNo",
                   "ID",
                   "Case.Number",
                   "Date",
                   "Block",
                   "IUCR",
                   "Primary.Type",
                   "Description",
                   "Location.Description",
                   "Arrest",
                   "Domestic",
                   "Beat",
                   "District",
                   "Ward",
                   "Community.Area",
                   "FBI.Code",
                   "X.Coordinate",
                   "Y.Coordinate",
                   "Year",
                   "Updated.On",
                   "Latitude",
                   "Longitude",
                   "Location")

答案 1 :(得分:0)

这是读取脚本的一个版本,该脚本解析文件第一行中的列名,并使用tidyr::gather()gsub()的组合来清除它们,并将它们用作{ {1}}。然后,它汇总read::read_csv()字段以确认其最大值6254267与文件最后一行中的行号匹配。

Row.Number

...以及输出:

library(readr)
library(tidyr)
# read first row and clean column names
colNamesData <- read_csv("./data/Chicago_Crimes_2005_to_2007.csv",col_names=FALSE,n_max=1)
# set NA to Row Number
colNamesData[1,1] <- "Row Number"
# use tidyr::gather() to turn rows into columns
xColNames <- gather(colNamesData)
# use gsub() to replace blanks with periods so data can be used as column names
xColNames$value <- gsub(" ",".",xColNames$value)
# read with readr::read_csv() and set column names to data extracted from first row
# skip first row because it contains bad column names and is missing the first column name 
crimeData <- read_csv("./data/Chicago_Crimes_2005_to_2007.csv",col_names=xColNames$value,skip=1)
# last row in file is row number 6254267
summary(crimeData$Row.Number)

注意::该文件无法正确读取所有记录,因为在行533,719处,记录似乎以变量名的冗余列表结尾。

enter image description here

要解决此问题,必须手动编辑数据以删除变量名的冗余列表,或者在错误周围进行编码。

有趣的是,原始数据文件的行533,720中的行号计数从0重新开始,这表明创建此数据的人员错误地将多个文件连接起来以创建此数据文件。