如何使用R避免CSV导入中的引号

时间:2018-02-07 13:26:22

标签: r csv

我在使用R:

读取下面的csv文件(提取)时遇到问题
id,created_date,stars,charity_id,user_id,is_anonymous,user_country_id
"1,""2016-08-10 12:50:30"",100,65536,32772,NULL,110"
"65,""2016-11-09 07:57:32"",50,425986,2686978,1,110"
"66,""2016-11-09 08:07:51"",50,393217,753673,0,110"

df <- read_csv("don.csv", quote = "")

给了我单元格中的qoutes,我之后可以处理,但是在导入过程中不能更顺利地完成吗?

2 个答案:

答案 0 :(得分:3)

1)如果输入中除了我们不想要的输入之外没有引号,那么这将起作用。如果输入来自文件,请将textConnection(Lines)替换为"don.csv"

L <- readLines(textConnection(Lines))
read.csv(text = gsub('"', '', L))

,并提供:

  id        created_date stars charity_id user_id is_anonymous user_country_id
1  1 2016-08-10 12:50:30   100      65536   32772         NULL             110
2 65 2016-11-09 07:57:32    50     425986 2686978            1             110
3 66 2016-11-09 08:07:51    50     393217  753673            0             110

2)同时假设双引号都是不需要的,另一种可能性是:

read.csv(pipe("sed 's/\042//g' don.csv"))

在Windows上,您需要安装Rtool并在您的路径上才能使用此功能,或者如果不在您的路径上,请提供完整路径,例如: "C:\\Rtools\\bin\\sed"

注意

输入Lines是:

Lines <-
'id,created_date,stars,charity_id,user_id,is_anonymous,user_country_id
"1,""2016-08-10 12:50:30"",100,65536,32772,NULL,110"
"65,""2016-11-09 07:57:32"",50,425986,2686978,1,110"
"66,""2016-11-09 08:07:51"",50,393217,753673,0,110"'

答案 1 :(得分:0)

您可以使用:

d <- read.table(sep='"', skip=1, text=
'id,created_date,stars,charity_id,user_id,is_anonymous,user_country_id
"1,""2016-08-10 12:50:30"",100,65536,32772,NULL,110"
"65,""2016-11-09 07:57:32"",50,425986,2686978,1,110"
"66,""2016-11-09 08:07:51"",50,393217,753673,0,110"'
)
d2 <- read.table(text=paste0(d$V2, d$V6), sep=",")
# or d2 <- read.table(text=paste0(d$V2, d$V6), sep=",", na.strings = "NULL")

(对于您的文件,您必须使用file="don.csv"而不是我的text=...。)
结果是

# d
#   V1  V2 V3                  V4 V5                        V6 V7
# 1 NA  1, NA 2016-08-10 12:50:30 NA ,100,65536,32772,NULL,110 NA
# 2 NA 65, NA 2016-11-09 07:57:32 NA  ,50,425986,2686978,1,110 NA
# 3 NA 66, NA 2016-11-09 08:07:51 NA   ,50,393217,753673,0,110 NA
# d2
#   V1 V2  V3     V4      V5   V6  V7
# 1  1 NA 100  65536   32772 NULL 110
# 2 65 NA  50 425986 2686978    1 110
# 3 66 NA  50 393217  753673    0 110

最终,您要重命名列并将列与cbind()组合在一起 您可以获得的列的名称:

cnames <- read.table(sep=',', nrows=1, text=
'id,created_date,stars,charity_id,user_id,is_anonymous,user_country_id
"1,""2016-08-10 12:50:30"",100,65536,32772,NULL,110"
"65,""2016-11-09 07:57:32"",50,425986,2686978,1,110"
"66,""2016-11-09 08:07:51"",50,393217,753673,0,110"'
)
as.character(unlist(cnames[1,]))

(对于您的文件,您必须使用file="don.csv"而不是text=...。)

您文件的完整代码:

cnames <- read.table(sep=',', nrows=1, file="don.csv")
H <- as.character(unlist(cnames[1,]))

d <- read.table(sep='"', skip=1, file="don.csv")
d2 <- read.table(text=paste0(d$V2, d$V6), sep=",", na.strings = "NULL")
d.d2 <- cbind(d[, 4], d2[, -2])
names(d.d2) <- H[c(2, 1, 3:7)]
d.d2