r - 当某些行包含逗号作为千位分隔符和“标志并且没有小数的行没有标志时,如何读取R中的数据

标签 r fread read.csv readr csv-import

我在 R 中加载一个 csv(以逗号分隔),其中引号 " 包含包含小数值列的每一行,并且特定值用双引号括起来 "" ,没有此问题的行没有 " 换行

csv 文件如下所示:

YEAR,COUNTRY,VALUE_A,VALUE_B
2019,SPAIN, 2000, 300
"2019,SPAIN,""2000,54"",300"
"2014,SPAIN,""2003,223"",""125,057"""
2018,FRANCE,1900,280

最佳答案

那太棒了...我能想到的最好的方法是将其作为文本读取,然后使用 gsub 清除千位标记和双引号。

# Read the csv as text, so we can run it through gsub
#
file_connection <- file("path_to_csv.csv")
text <- readLines(file_connection)
close(file_connection)

将 csv 的内容读取为字符串后,我们可以处理文本“格式化”

# 1. Remove the comma as thousand mark
# There HAS to be a better way to do this regex but I couldn't remember
#
sanitized_mark <- gsub('(\\"\\"[0-9]+),([0-9]+\\"\\")', '\\1\\2', text)

# 2. Remove all double quotes
# 
sanitized_quotes <- gsub('\\"', '', sanitized_mark)

# Paste it all together adding a newline character after each element
#
sanitized <- paste0(sanitized_quotes, collapse="\n")

可以使用 text 参数读取生成的字符串,就好像它是 .csv 的内容

df <- read.csv(text=sanitized)

关于r - 当某些行包含逗号作为千位分隔符和“标志并且没有小数的行没有标志时,如何读取R中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60063990/

相关文章:

r - read.table() 和 read.csv() 中的 skipNul = TRUE 有什么作用(除了跳过/忽略嵌入的空值)?

r - R中的按元素均值

r - ggplot : no sign on y-axis-labels 中的数字格式

c - 函数 fread 不以\0 终止字符串

r - 是否可以在 data.table 包中直接 fread 跳过错误的行

R 的 read.csv() 省略行

R read.csv 如何忽略回车?

r - 使用 R 进行分区和排列

通过 mutate_at 中的名称片段引用其他列

C编程-将文件复制到另一个