如何将数据从R导出到CSV、Excel
如何从R导出数据
在本教程中,我们将学习如何将数据从R环境导出为不同的格式。
要将数据导出到硬盘,您需要文件路径和扩展名。首先,路径是数据将存储的位置。在本教程中,您将看到如何将数据存储在
- 硬盘上
- Google Drive
- Dropbox
其次,R允许用户将数据导出为不同类型的文件。我们涵盖了基本文件的扩展名
- csv
- xlsx
- RDS
- SAS
- SPSS
- STATA
总的来说,从R导出数据并不难。
导出到硬盘
首先,您可以将数据直接保存在工作目录中。以下代码将打印出您的工作目录路径
directory <-getwd() directory
输出
## [1] "/Users/15_Export_to_do"
默认情况下,文件将保存在下面的路径中。
适用于Mac OS
/Users/USERNAME/Downloads/
适用于 Windows
C:\Users\USERNAME\Documents\
当然,您可以设置一个不同的路径。例如,您可以将路径更改为下载文件夹。
创建数据框
首先,让我们导入mtcars数据集,并按gear对mpg和disp进行分组求平均值。
library(dplyr) df <-mtcars % > % select(mpg, disp, gear) % > % group_by(gear) % > % summarize(mean_mpg = mean(mpg), mean_disp = mean(disp)) df
输出
## # A tibble: 3 x 3 ## gear mean_mpg mean_disp ## <dbl> <dbl> lt;dbl> ## 1 3 16.10667 326.3000 ## 2 4 24.53333 123.0167 ## 3 5 21.38000 202.4800
该表包含三行三列。您可以使用R中的write.csv函数创建CSV文件。
如何在R中将DataFrame导出为CSV文件
write.csv在R中用于将DataFrame导出为CSV的基本语法
write.csv(df, path) arguments -df: Dataset to save. Need to be the same name of the data frame in the environment. -path: A string. Set the destination path. Path + filename + extension i.e. "/Users/USERNAME/Downloads/mydata.csv" or the filename + extension if the folder is the same as the working directory
示例
write.csv(df, "table_car.csv")
代码解释
- write.csv(df, “table_car.csv”):在硬盘上创建CSV文件
- df:环境中数据框的名称
- “table_car.csv”:将文件命名为table_car并将其存储为csv
注意:您可以使用write.csv2()函数来分隔行,用分号代替,以供R导出为csv数据。
write.csv2(df, "table_car.csv")
注意:仅为教学目的,我们创建了一个名为open_folder()的函数来为您打开目录文件夹。您只需运行下面的代码,看看csv文件存储在哪里。您应该看到一个名为table_car.csv的文件,用于R导出为csv的数据。
# Run this code to create the function open_folder <-function(dir){ if (.Platform['OS.type'] == "windows"){ shell.exec(dir) } else { system(paste(Sys.getenv("R_BROWSER"), dir)) } } # Call the function to open the folder open_folder(directory)
如何将R中的数据导出为Excel文件
现在,我们将学习如何将数据从R导出到Excel。
对于Windows用户来说,从R导出数据到Excel非常简单,而对于Mac OS用户来说则有点棘手。两类用户都将使用xlsx库来创建Excel文件。唯一的区别在于库的安装。确实,xlsx库使用Java来创建文件。如果您的机器上没有安装Java,则需要安装Java才能进行R数据导出到Excel。
Windows用户
如果您是Windows用户,您可以使用conda直接安装库,以便将数据框导出为Excel R。
conda install -c r r-xlsx
安装库后,您可以使用write.xlsx()函数。将在工作目录中为R导出Excel数据创建一个新的Excel工作簿。
library(xlsx) write.xlsx(df, "table_car.xlsx")
如果您是Mac OS用户,您需要遵循以下步骤
- 步骤1:安装最新版本的Java
- 步骤2:安装rJava库
- 步骤3:安装xlsx库
步骤1)您可以从Oracle官方网站下载Java并安装它。
您可以返回Rstudio并检查已安装的Java版本。
system("java -version")
在教程进行时,Java的最新版本是9.0.4。
步骤2)您需要在R中安装rjava。我们建议您使用Anaconda安装R和Rstudio。Anaconda管理库之间的依赖关系。从这个意义上说,Anaconda将处理rJava安装的复杂性。
首先,您需要更新conda,然后安装库。您可以将以下两行代码复制并粘贴到终端中。
conda - conda update conda install -c r r-rjava
接下来,在Rstudio中打开rjava。
library(rJava)
步骤3)最后,是时候安装xlsx了。同样,您可以使用conda来完成。
conda install -c r r-xlsx
与Windows用户一样,您可以使用write.xlsx()函数保存数据。
library(xlsx)
输出
## Loading required package: xlsxjars
write.xlsx(df, "table_car.xlsx")
将R中的数据导出到不同的软件
将数据导出到不同的软件和导入它们一样简单。库“haven”提供了一种方便的方式来导出数据到
- spss
- sas
- stata
首先,导入库。如果您没有“haven”,您可以点击这里进行安装。
library(haven)
SPSS文件
以下是将数据导出到SPSS软件的代码
write_sav(df, "table_car.sav")
将R中的数据导出为SAS文件
就像spss一样简单,您可以导出到sas。
write_sas(df, "table_car.sas7bdat")
如何将R中的数据导出为STATA文件
最后,haven库允许写入.dta文件。
write_dta(df, "table_car.dta")
回车符
如果您想保存一个数据框或任何其他R对象,您可以使用save()函数。
save(df, file ='table_car.RData')
您可以在当前工作目录中检查上面创建的文件。
与云服务交互
最后但同样重要的是,R配备了强大的库来与云计算服务进行交互。本教程的最后一部分将介绍从以下位置导出/导入文件:
- Google Drive
- Dropbox
注意:本教程的这一部分假定您拥有Google和Dropbox账户。如果没有,您可以快速创建一个——Google Drive:https://#/SignUp?hl=en——Dropbox:https://www.dropbox.com/h
Google Drive
您需要安装googledrive库来访问允许与Google Drive交互的函数。
该库尚未在Anaconda中提供。您可以在控制台中通过以下代码安装它。
install.packages("googledrive")
然后您打开库。
library(googledrive)
对于非conda用户,安装库很容易,您可以使用函数install.packages(‘PACKAGE NAME’)并将包的名称放在括号中。不要忘记‘ ‘。请注意,R应该会自动将包安装到 `libPaths()` 中。看看它是如何工作的还是值得的。
上传到Google Drive
要将文件上传到Google Drive,您需要使用drive_upload()函数。
每次重启Rstudio时,系统都会提示您允许tidyverse访问Google Drive。
drive_upload()的基本语法是
drive_upload(file, path = NULL, name = NULL) arguments: - file: Full name of the file to upload (i.e., including the extension) - path: Location of the file- name: You can rename it as you wish. By default, it is the local name.
启动代码后,您需要确认几个问题。
drive_upload%<("table_car.csv", name ="table_car")
输出
## Local file: ## * table_car.csv ## uploaded into Drive file: ## * table_car: 1hwb57eT-9qSgDHt9CrVt5Ht7RHogQaMk ## with MIME type: ## * text/csv
您在控制台中输入1以确认访问。
然后,您将被重定向到Google API以允许访问。点击允许。
身份验证完成后,您可以关闭浏览器。
在Rstudio的控制台中,您可以看到所完成步骤的摘要。Google已成功上传了本地位于Drive上的文件。Google为Drive中的每个文件分配了一个ID。
您可以在Google Spreadsheet中看到此文件。
drive_browse("table_car")
输出
您将被重定向到Google Spreadsheet。
从Google Drive导入
通过ID上传文件到Google Drive很方便。如果您知道文件名,您可以按以下方式获取其ID:
注意:根据您的互联网连接和Drive的大小,这需要一些时间。
x <-drive_get("table_car") as_id(x)
您将ID存储在变量x中。drive_download()函数允许从Google Drive下载文件。
基本语法是
drive_download(file, path = NULL, overwrite = FALSE) arguments: - file: Name or id of the file to download -path: Location to download the file. By default, it is downloaded to the working directory and the name as in Google Drive -overwrite = FALSE: If the file already exists, don't overwrite it. If set to TRUE, the old file is erased and replaced by the new one.
您最终可以下载文件。
download_google & lt; - drive_download(as_id(x), overwrite = TRUE)
代码解释
- drive_download():从Google Drive下载文件的函数
- as_id(x):使用ID在Google Drive中浏览文件
- overwrite = TRUE:如果文件存在,则覆盖它,否则执行将中止。要查看本地文件的名称,您可以使用
输出
文件存储在您的工作目录中。请记住,您需要在R中打开它之前添加文件的扩展名。您可以使用paste()函数创建完整的文件名(即table_car.csv)。
google_file <-download_google$local_path google_file path <-paste(google_file, ".csv", sep = "") google_table_car <-read.csv(path) google_table_car
输出
## X gear mean_mpg mean_disp ## 1 1 3 16.10667 326.3000 ## 2 2 4 24.53333 123.0167 ## 3 3 5 21.38000 202.4800
最后,您可以从Google Drive中删除该文件。
## remove file drive_find("table_car") %>%drive_rm()
输出
这是一个缓慢的过程。删除需要时间。
导出到Dropbox
R通过rdrop2库与Dropbox进行交互。该库也不在Anaconda中提供。您可以通过控制台安装它。
install.packages('rdrop2')
library(rdrop2)
您需要提供对Dropbox的临时访问权限并提供您的凭证。在识别完成后,R可以创建、删除、上传和下载到您的Dropbox。
首先,您需要授予对您账户的访问权限。凭证会在整个会话期间缓存。
drop_auth()
您将被重定向到Dropbox以确认身份验证。
您将看到一个确认页面。您可以关闭它并返回R。
您可以使用drop_create()函数创建一个文件夹。
- drop_create(‘my_first_drop’):在Dropbox的第一个分支中创建一个文件夹。
- drop_create(‘First_branch/my_first_drop’):在已存在的First_branch文件夹内创建一个文件夹。
drop_create('my_first_drop')
输出
在Dropbox中
要将.csv文件上传到您的Dropbox,请使用drop_upload()函数。
基本语法
drop_upload(file, path = NULL, mode = "overwrite") arguments: - file: local path - path: Path on Dropbox - mode = "overwrite": By default, overwrite an existing file. If set to `add`, the upload is not completed.
drop_upload('table_car.csv', path = "my_first_drop")
输出
在Dropbox中
您可以使用drop_read_csv()函数从Dropbox读取csv文件。
dropbox_table_car <-drop_read_csv("my_first_drop/table_car.csv") dropbox_table_car
输出
## X gear mean_mpg mean_disp ## 1 1 3 16.10667 326.3000 ## 2 2 4 24.53333 123.0167 ## 3 3 5 21.38000 202.4800
当您完成使用该文件并想删除它时。您需要在drop_delete()函数中写入文件的路径。
drop_delete('my_first_drop/table_car.csv')
输出
也可以删除一个文件夹。
drop_delete('my_first_drop')
输出
摘要
我们可以在下表中总结所有函数。
库 | 目标 | 函数 |
---|---|---|
base | 导出csv | write.csv() |
xlsx | 导出Excel | write.xlsx() |
haven | 导出spss | write_sav() |
haven | 导出sas | write_sas() |
haven | 导出stata | write_dta() |
base | 导出R | save() |
googledrive | 上传到Google Drive | drive_upload() |
googledrive | 在Google Drive中打开 | drive_browse() |
googledrive | 检索文件ID | drive_get(as_id()) |
googledrive | 从Google Drive下载 | download_google() |
googledrive | 从Google Drive删除文件 | drive_rm() |
rdrop2 | 身份验证 | drop_auth() |
rdrop2 | 创建一个文件夹 | drop_create() |
rdrop2 | 上传到Dropbox | drop_upload() |
rdrop2 | 从Dropbox读取csv | drop_read_csv |
rdrop2 | 从Dropbox删除文件 | drop_delete() |