这个问题在这里已经有了答案:
Read a UTF-8 text file with BOM
(2 个回答)
5年前关闭。
有时一个字节顺序标记 (BOM) 出现在 .CSV 文件的开头。当您使用记事本或 Excel 打开文件时,该符号是不可见的,但是,当您使用各种方法在 R 中读取文件时,第一列的名称中会出现不同的符号。这是一个例子
开头带有 BOM 的示例 csv 文件。
ID,title,clean_title,clean_title_id
1,0 - 0,,0
2,"""0 - 1,000,000""",,0
27448,"20yr. rope walker
igger",Rope Walker Igger,1832700817
通读
read.csv
在基础 R 包中(x1 = read.csv("file1.csv",stringsAsFactors = FALSE))
# ï..ID raw_title semi_clean semi_clean_id
# 1 1 0 - 0 0
# 2 2 "0 - 1,000,000" 0
# 3 27448 20yr. rope walker\nigger Rope Walker Igger 1832700817
通读
fread
在 data.table 包中(x2 = data.table::fread("file1.csv"))
# ID raw_title semi_clean semi_clean_id
# 1: 1 0 - 0 0
# 2: 2 ""0 - 1,000,000"" 0
# 3: 27448 20yr. rope walker\rigger Rope Walker Igger 1832700817
通读
read_csv
在阅读器包中(x3 = readr::read_csv("file1.csv"))
# <U+FEFF>ID raw_title semi_clean semi_clean_id
# 1 1 0 - 0 <NA> 0
# 2 2 "0 - 1,000,000" <NA> 0
# 3 27448 20yr. rope walker\rigger Rope Walker Igger 1832700817
您可以注意到变量名称 ID 前面的不同字符。
这是在所有这些上运行名称时的结果
names(x1)
# [1] "ï..ID" "raw_title" "semi_clean" "semi_clean_id"
names(x2)
# [1] "ID" "raw_title" "semi_clean" "semi_clean_id"
names(x3)
# [1] "ID" "raw_title" "semi_clean" "semi_clean_id"
在
x3
,在 ID
前面没有任何“可见”的东西,但是当你检查names(x3)[[1]]=="ID"
# [1] FALSE
如何在每种情况下摆脱这些不需要的字符。
PS:请添加更多读取csv文件的方法,遇到的问题和解决方案。
最佳答案
对于 base R 中的 read.csv 使用:
x1 = read.csv("file1.csv",stringsAsFactors = FALSE, fileEncoding = "UTF-8-BOM")
对于 fread,请使用:
x2 = fread("file1.csv")
setnames(x2, "ID", "ID")
对于 read_csv,请使用:
x3 = readr::read_csv("file1.csv")
setDT(X3) #convert into data tables, so that setnames can be used
setnames(x3, "\uFEFFID", "ID")
一种基于非 R 的解决方案是在 Notepad++ 中打开文件,将编码更改为“无 BOM 的 UTF-8 编码”后保存文件
关于r - 处理 R 中的字节顺序标记 (BOM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39593637/