read.csv中的多字节字符串无效

jar*_*ard 40 r read.csv

我正在尝试导入日语的csv.这段代码:

url <- 'http://www.mof.go.jp/international_policy/reference/itn_transactions_in_securities/week.csv'
x <- read.csv(url, header=FALSE, stringsAsFactors=FALSE)
Run Code Online (Sandbox Code Playgroud)

返回以下错误:

Error in type.convert(data[[i]], as.is = as.is[i], dec = dec, na.strings = character(0L)) : 
invalid multibyte string at '<91>?O<8b>y<82>??<e0><8f>?<94><94><84><94><83><8c>_<96>?@(<8f>T<8e><9f><81>E<8e>w<92><e8><95>@<8a>?x<81>[<83>X<81>j'
Run Code Online (Sandbox Code Playgroud)

我试图改变的编码(Encoding(url) <- 'UTF-8'和也为latin1),并试图除去read.csv参数,但在每种情况下接收相同的"无效多字节字符串"消息.是否有应使用不同的编码,或者是有一些其他的问题吗?

Jos*_*ich 75

Encoding设置字符串的编码.它不会设置由字符串表示的文件的编码,这是您想要的.

在尝试之后,这对我有用"UTF-8":

x <- read.csv(url, header=FALSE, stringsAsFactors=FALSE, fileEncoding="latin1")
Run Code Online (Sandbox Code Playgroud)

您可能希望跳过前16行,并分别读入标题.无论哪种方式,仍然需要做很多清理工作.

x <- read.csv(url, header=FALSE, stringsAsFactors=FALSE,
  fileEncoding="latin1", skip=16)
# get started with the clean-up
x[,1] <- gsub("\u0081|`", "", x[,1])    # get rid of odd characters
x[,-1] <- as.data.frame(lapply(x[,-1],  # convert to numbers
  function(d) type.convert(gsub(d, pattern=",", replace=""))))
Run Code Online (Sandbox Code Playgroud)


use*_*684 10

您可能遇到过此问题,因为系统区域设置不兼容尝试使用此代码设置系统区域设置 Sys.setlocale("LC_ALL", "C")


Je *_*ers 7

来自tidyverse宇宙的readr包可能会有所帮助.

您可以read_csv()使用local()函数及其encoding参数通过函数的local参数设置编码:

read_csv(file = "http://www.mof.go.jp/international_policy/reference/itn_transactions_in_securities/week.csv",
         skip = 14,
         local = locale(encoding = "latin1"))
Run Code Online (Sandbox Code Playgroud)