我的系统是windowns 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.即使#library(haven)#读取spss
,仍然会导致Rstudio错误。
2.我无法更改语言环境English_United States.1252
如何解决Rstudio问题?
答案 0 :(得分:0)
这是一个解决方案。永远让我把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='readonly',
password='readonly',
client.flag=CLIENT_MULTI_STATEMENTS,
dbname='atw',
host='116.228.235.182',
port=6000)
# 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")