R语言读取Excel文件的一系列陷阱

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jining11/article/details/81676865

你想用R读取一个Excel文件,你觉得这事没啥难的,就像所有的文件读取,只需要知道文件名就万事大吉了。 于是,你把1.xls放到读取.R的文件夹下面,重命名为1.csv,打开rstudio,执行下面这条语句

a <- read.csv("1.csv")

出现了下面的报错

Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") : cannot open file '1.csv': No such file or directory

很显然,文件并不在当前的路径中,那当前的路径是什么呢?

接下来,执行获取当前工作路径的语句

> getwd()
[1] "C:/Users/13371/Documents"

这应该是rstudio默认的工作路径了,那么,如何才能将工作路径更改为文件所在的路径呢?一个显而易见的方法是使用setwd(···)或者是在菜单中手动设置,但这样很麻烦,而且每次打开都要来一次,经过不懈查找,你终于找到了解决方案。

script.dir <- dirname(sys.frame(1)$ofile)
setwd(script.dir)

但是如果文件在一个很远的地方,那该怎么办呢?

# 这样就可以自己选择文件了
b <- read.csv(file.choose())

按下run执行,咦,怎么又弹出了这个你看都看不懂的报错呢?

> script.dir <- dirname(parent.frame(2)$ofile)
Error in dirname(parent.frame(2)$ofile) : 
  a character vector argument expected

经过一番尝试才知道,必须要使用source模式一次性执行完才可以,而这其中缘由你还是不太明白,希望有大佬可以指点迷津。

那,总可以运行了吧,还是不行,会报这样的错误。

> a <- read.csv("1.csv")
Error in make.names(col.names, unique = TRUE) : 
  invalid multibyte string 1
In addition: Warning message:
In read.table(file = file, header = header, sep = sep, quote = quote,  :
  incomplete final line found by readTableHeader on '1.csv'

这是说CSV的格式不符合要求,这是因为简单粗暴地改扩展名并不能得到一个正确的编码。你需要规规矩矩地用Excel表打开,并且在另存为里面的文件格式下面勾选下图所示的标准。

扫描二维码关注公众号,回复: 3124548 查看本文章

第一次执行时会报这样的错误,但你什么也不需要做,再来一次,什么都不会发生。

Warning messages:
1: In grepl("|||", what, fixed = TRUE) :
  input string 1 is invalid in this locale
2: In grepl("|||", what, fixed = TRUE) :
  input string 1 is invalid in this locale

这样就没有任何问题了,随随便便求某一列的均值方差:

> mean(a$X5.您的年龄是)
[1] 4.617391
> sd(a$X5.您的年龄是)
[1] 0.7560587

猜你喜欢

转载自blog.csdn.net/jining11/article/details/81676865
今日推荐