Excel 文件
优质
小牛编辑
129浏览
2023-12-01
Microsoft Excel是使用最广泛的电子表格程序,它以.xls或.xlsx格式存储数据。 R可以使用一些特定于Excel的包直接从这些文件中读取。 很少有这样的软件包 - XLConnect,xlsx,gdata等。我们将使用xlsx软件包。 R也可以使用这个包写入excel文件。
安装xlsx包
您可以在R控制台中使用以下命令来安装“xlsx”软件包。 它可能会要求安装一些此软件包所依赖的附加软件包。 使用具有所需包名称的相同命令来安装其他包。
install.packages("xlsx")
验证并加载“xlsx”包
使用以下命令验证并加载“xlsx”软件包。
# Verify the package is installed.
any(grepl("xlsx",installed.packages()))
# Load the library into R workspace.
library("xlsx")
运行脚本时,我们得到以下输出。
[1] TRUE
Loading required package: rJava
Loading required package: methods
Loading required package: xlsxjars
输入为xlsx文件
打开Microsoft excel。 将以下数据复制并粘贴到名为sheet1的工作表中。
id name salary start_date dept
1 Rick 623.3 1/1/2012 IT
2 Dan 515.2 9/23/2013 Operations
3 Michelle 611 11/15/2014 IT
4 Ryan 729 5/11/2014 HR
5 Gary 43.25 3/27/2015 Finance
6 Nina 578 5/21/2013 IT
7 Simon 632.8 7/30/2013 Operations
8 Guru 722.5 6/17/2014 Finance
同时将以下数据复制并粘贴到另一个工作表,并将此工作表重命名为“city”。
name city
Rick Seattle
Dan Tampa
Michelle Chicago
Ryan Seattle
Gary Houston
Nina Boston
Simon Mumbai
Guru Dallas
将Excel文件另存为“input.xlsx”。 您应该将其保存在R工作区的当前工作目录中。
阅读Excel文件
使用read.xlsx()函数读取read.xlsx() ,如下所示。 结果存储为R环境中的数据帧。
# Read the first worksheet in the file input.xlsx.
data <- read.xlsx("input.xlsx", sheetIndex = 1)
print(data)
当我们执行上面的代码时,它会产生以下结果 -
id, name, salary, start_date, dept
1 1 Rick 623.30 2012-01-01 IT
2 2 Dan 515.20 2013-09-23 Operations
3 3 Michelle 611.00 2014-11-15 IT
4 4 Ryan 729.00 2014-05-11 HR
5 NA Gary 843.25 2015-03-27 Finance
6 6 Nina 578.00 2013-05-21 IT
7 7 Simon 632.80 2013-07-30 Operations
8 8 Guru 722.50 2014-06-17 Finance