
2.1 读取数据
R语言常调用read.table()、read.csv()或scan()函数来读取存储在文本文件(ASCII)中的数据,read.table()函数主要用于数据框中的操作,可以直接把整个外部文件读入数据框对象。
外部文件常要求有特定的格式,例如:
(1)第一排(Line)可以是表头(Header),包含各列数据的变量名称(Variable Name)。不过表头也可以省略。
(2)其余各排是各行的值。
要读取在R的工作目录中的X.csv文件(见表2-1),可执行如下的指令:
表2-1 X.csv文件


注意,CSV文件中的数据是用逗号分隔开的,所以加入sep=","来指定分隔符是逗号。若header=FALSE,则使用默认的V1,V2,…,V#来作为表头(header)的名称。

也可以调用read.csv()函数:

可以使用Excel将X.csv转成X.txt文件(请使用文本文件,而不要使用Unicode字符编码的文件),再将文件读入。若文件中有中文,则需先确认文件中的字符编码,转换文件的字符编码后再将文件读入。MacOS操作系统默认的字符编码是UTF-8,而Windows操作系统的中文版默认的字符编码是GBK(简体字)或Big5(繁体字)。使用Windows操作系统时,我们可以用notepad打开CSV文件,再另存为UTF-8编码的文件,而后再读入文件。
读取网络上的iris.csv,地址为https://github.com/rashida048/Datasets/blob/master/iris.csv:

或读取网络上的iris.table,地址为https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data:

R 4.0以上版本最重要的更新便是导入的字符串数据不再被默认转换成因子变量(Factor),过去stringsAsFactors选项默认为TRUE,因此导入的字符串数据都会被转换成因子变量,但是在新版本中,stringsAsFactors选项默认为FALSE。

scan()函数比read.table()函数更加灵活,因为scan()函数可接受键盘输入的数据:

scan()函数也可以指定输入数据的数据类型,例如要创建列表对象:

其中:
· file:文件路径,file=""表示由键盘输入值。
· what:设置输入值的数据类型,上述例子为创建列表对象,且其第一个元素name=""表示字符串,第二个元素pay=integer(0)表示整数,而第三个元素sex=""也是字符串。
scan()函数也可以读取CSV文件和文本文件,表2-2所示为X1.csv文件。
表2-2 X1.csv文件


使用Excel将X1.csv转换成X1.txt文件再读入:
