R - Excel 文件
R 语言与 Excel 文件:现代方法
Section titled “R 语言与 Excel 文件:现代方法”Microsoft Excel(.xls、.xlsx)是一种无处不在的电子表格程序。与 Excel 文件交互是数据分析中的常见任务。虽然有多个包可以将 R 语言与 Excel 连接起来,但现代标准是使用 readxl 和 writexl 包。
为什么选择 readxl 和 writexl?
像 xlsx 或 gdata 这样的旧包通常依赖于 Java 或 Perl,这可能导致速度慢且设置困难。而 readxl 和 writexl 包具有以下优点:
- 速度快:它们使用 C/C++ 编写,性能高。
- 无依赖:它们没有像 Java 这样的外部依赖,使得在任何系统上的安装和使用都非常顺畅。
- 与 Tidyverse 兼容:
readxl是核心tidyverse的一部分,并且与dplyr和ggplot2等其他包配合良好。
步骤 1:安装所需包
Section titled “步骤 1:安装所需包”你可以在 R 控制台中运行以下命令,从 CRAN(R 综合档案网络)安装这两个包。
install.packages(c("readxl", "writexl"))步骤 2:准备 Excel 输入文件
Section titled “步骤 2:准备 Excel 输入文件”创建一个名为 input.xlsx 的 Excel 文件。在第一个工作表(通常默认名为 Sheet1)中,输入以下员工数据:
id name salary start_date dept1 Rick 623.3 2012-01-01 IT2 Dan 515.2 2013-09-23 Operations3 Michelle 611 2014-11-15 IT4 Ryan 729 2014-05-11 HR5 Gary 843.25 2015-03-27 Finance6 Nina 578 2013-05-21 IT7 Simon 632.8 2013-07-30 Operations8 Guru 722.5 2014-06-17 Finance接下来,创建第二个工作表并将其命名为 cities。输入以下地点数据:
name cityRick SeattleDan TampaMichelle ChicagoRyan SeattleGary HoustonNina BostonSimon MumbaiGuru Dallas将文件 input.xlsx 保存到你的 R 项目的工作目录中。
步骤 3:从 Excel 文件读取数据
Section titled “步骤 3:从 Excel 文件读取数据”我们使用 readxl 包中的 read_excel() 函数。结果将作为 tibble(一种现代数据框)导入。
# 加载库library(readxl)
# 按索引(基于 1 的)读取第一个工作表# 如果未指定,read_excel() 足够智能,会自动查找第一个工作表。employee_data <- read_excel("input.xlsx", sheet = 1)print(employee_data)
# 按名称读取第二个工作表city_data <- read_excel("input.xlsx", sheet = "cities")print(city_data)当我们执行上述代码时,会产生以下输出:
# A tibble: 8 × 5 id name salary start_date dept <dbl> <chr> <dbl> <dttm> <chr>1 1 Rick 623. 2012-01-01 00:00:00 IT2 2 Dan 515. 2013-09-23 00:00:00 Operations3 3 Michelle 611 2014-11-15 00:00:00 IT4 4 Ryan 729 2014-05-11 00:00:00 HR5 5 Gary 843. 2015-03-27 00:00:00 Finance6 6 Nina 578 2013-05-21 00:00:00 IT7 7 Simon 633. 2013-07-30 00:00:00 Operations8 8 Guru 722. 2014-06-17 00:00:00 Finance
# A tibble: 8 × 2 name city <chr> <chr>1 Rick Seattle2 Dan Tampa3 Michelle Chicago4 Ryan Seattle5 Gary Houston6 Nina Boston7 Simon Mumbai8 Guru Dallas步骤 4:将数据写入 Excel 文件
Section titled “步骤 4:将数据写入 Excel 文件”writexl 包使用 write_xlsx() 函数,使得将数据框或 tibble 写入 .xlsx 文件变得极其简单。
假设我们已经合并了两个数据集,并希望导出结果。
# 加载必要的库library(writexl)library(dplyr)
# 合并之前导入的两个数据集full_data <- left_join(employee_data, city_data, by = "name")
# 将合并后的数据写入新的 Excel 文件# 文件将在你的工作目录中创建write_xlsx(full_data, path = "output_data.xlsx")
cat("Successfully wrote combined data to output_data.xlsx")运行此代码后,你的项目文件夹中将出现一个名为 output_data.xlsx 的新文件,其中包含合并后的数据。你甚至可以通过将多个数据框作为命名列表传递,将它们写入同一个文件的不同工作表:
# 写入多个工作表的示例list_of_datasets <- list("Employees" = employee_data, "Locations" = city_data)write_xlsx(list_of_datasets, path = "multisheet_output.xlsx")