我正在处理来自问卷的SPSS数据,该问卷必须源自M $ Word.Word会自动将连字符更改为长连字符,并转换为无法正确显示的字符,即" - "变为"ú".
我的问题:WINDOWS-1252字符集中的utf8ToInt()等价是什么?
utf8ToInt("A")
[1] 65
Run Code Online (Sandbox Code Playgroud)
当我使用自己的数据执行此操作时,出现错误:
x <- str_sub(levels(sd$j1)[1], 7, 7)
print(x)
[1] "ú"
utf8ToInt(x)
Error in utf8ToInt(x) : invalid UTF-8 string
Run Code Online (Sandbox Code Playgroud)
但是,x的内容在grep和gsub表达式中完全可用.
> Sys.getlocale()
[1] "LC_COLLATE=English_United Kingdom.1252;LC_CTYPE=English_United Kingdom.1252;LC_MONETARY=English_United Kingdom.1252;LC_NUMERIC=C;LC_TIME=English_United Kingdom.1252"
Run Code Online (Sandbox Code Playgroud)
如果您通过表单包外部加载SPSS sav文件,您可以通过指定编码来轻松导入具有正确编码的数据帧:read.spss
read.spss("foo.sav", reencode="CP1252")
Run Code Online (Sandbox Code Playgroud)
经过一些头疼,大量的阅读帮助文件和反复试验,我创建了两个小功能,可以满足我的需求.这些函数的工作原理是将输入转换为UTF-8,然后返回UTF-8编码字符向量的整数向量,反之亦然.
# Convert character to integer vector
# Optional encoding specifies encoding of x, defaults to current locale
encToInt <- function(x, encoding=localeToCharset()){
utf8ToInt(iconv(x, encoding, "UTF-8"))
}
# Convert integer vector to character vector
# Optional encoding specifies encoding of x, defaults to current locale
intToEnc <- function(x, encoding=localeToCharset()){
iconv(intToUtf8(x), "utf-8", encoding)
}
Run Code Online (Sandbox Code Playgroud)
一些例子:
x <- "\xfa"
encToInt(x)
[1] 250
intToEnc(250)
[1] "ú"
Run Code Online (Sandbox Code Playgroud)