r - Rstudio 无法正确处理带有中文字符的评论
问题描述
我的系统是 windows 10,R 3.5.1,Rstudio 1.1.463
Rstudio 默认文本编码是UTF-8
.
library(RMySQL)
library(haven)#读取spss
Rstudio 中上述脚本的输出为:
> library(RMySQL)
> library(haven)#
Warning message:
In readLines(file, warn = FALSE) :
invalid input found on input connection '~/.active-rstudio-document'
在 R 中运行以上脚本时一切正常。
似乎Rstudio 无法阅读评论中的中文,然后导致错误。
然后我google了一下,看看是不是有locale
问题:
Sys.getlocale()
Sys.setlocale(category = "LC_ALL", locale = "en_US.UTF-8")
#library(RMySQL)
#library(haven)#读取spss
得到如下输出:
> source('~/.active-rstudio-document', encoding = 'UTF-8', echo=TRUE)
> Sys.getlocale()
[1] "LC_COLLATE=English_United States.1252;LC_CTYPE=English_United States.1252;LC_MONETARY=English_United States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252"
> Sys.setlocale(category = "LC_ALL", locale = "en_US.UTF-8")
[1] ""
> #library(RMySQL)
> #library(haven)#
Warning messages:
1: In readLines(file, warn = FALSE) :
invalid input found on input connection '~/.active-rstudio-document'
2: In Sys.setlocale(category = "LC_ALL", locale = "en_US.UTF-8") :
OS reports request to set locale to "en_US.UTF-8" cannot be honored
根据输出,我发现了 2 个问题:
1.Even#library(haven)#读取spss
仍然导致 Rstudio 出错。
2.我无法更改语言环境English_United States.1252
如何解决这个 Rstudio 问题?
解决方案
这是一个解决方案。花了我很长时间将 Sys.setlocale + SET NAMES gbk 解决方案放在一起,这最终奏效了。
library(RMySQL)
Sys.setlocale(category = "LC_ALL", locale = "chinese")
sqlQuery <- function (query) {
# creating DB connection object with RMysql package
DB <- dbConnect(MySQL(),
user='',
password='',
client.flag=CLIENT_MULTI_STATEMENTS,
dbname='',
host='',
port=)
# close db connection after function call exits
on.exit(dbDisconnect(DB))
dbSendQuery(DB,"SET NAMES gbk")
# send Query to btain result set
rs <- dbSendQuery(DB, query)
# get elements from result sets and convert to dataframe
result <- fetch(rs, -1)
# return the dataframe
return(result)
}
data <- sqlQuery("SELECT * FROM TABLENAME")
推荐阅读
- vba - 是否可以使用 VBA 将别名分配给查询的字段以供以后在报表中使用?
- amazon-web-services - Amazon RDS Snapshot 系统是一样的自动备份吗?
- r - 使用 dplyr 在列内创建新组
- sql - 考虑到主列中具有相同值的不同列中的另一个值
- asp.net-core - IDPmetadata url 在 IIS 服务器上给出问题 - ITfoxtec - 没有这样的主机是已知的
- java - 无法从 actionlistener 内部增加变量
- laravel - 队列未在 DigitalOcean 工作人员(AppPlatform)上处理
- javascript - React JS - 无法在尚未安装的组件上调用 setState
- android - IONIC:播放声音时淡出背景音乐(来自其他应用程序)
- bash - 如何打印与awk多次匹配的列的第一次出现