我在 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/