如何在R中使用sink()函数
您可以在R中使用sink()函数将数据发送到外部连接。
大家好,今天我们将探讨R中的sink()函数的应用。我们将尝试建立多种格式的连接,如文本和csv文件类型。
使用sink()函数,您可以打印数据或将数据或R输出导出到文本或CSV文件类型。
让我们看看它是如何工作的!
R中的sink()函数的语法
Sink()函数用于将在R中获得的输出驱动到外部连接。
sink(file = NULL, type = c("output", "message"),split = FALSE)
哪里:
(Where) 哪里。
- File = The editable connection or the file type.
- Append = The logical function used to append the data to file to avoid overwrite.
- Split = Output will be diverted to a new connection or link.
1. 建立工作目录
使用sink()函数的帮助下,你可以将输出作为一个连接轻松打印到文本文件中。我们可以通过设置工作目录来开始这个过程。
检查当前的工作目录。
#returns the current working directory
getwd()
"C:/Users/Dell/Desktop/rfiles"
好的。我们现在已经获取到了工作目录。而且你也可以使用以下方法来更改工作目录,
#sets the new working directory
setwd("The directory path here")
将路径粘贴到setwd()函数中以设置新的工作目录。之后不要忘记使用上面所示的’getwd()’命令来确认更改。
2. 将数据打印到文本文件中
希望你已经准备好了你的工作路径。现在我们要建立一个文件连接,并将一些数据打印到文件中。
让我们看看它是如何运作的。
#sinks the data into connection as text file
sink("my_first_sink.txt")
#prints numbers from 1 to 20
for (i in 1:20)
print(i)
sink()

现在你可以看到我们的 R 数据被整洁地打印到文本文件中了。真棒,是吧?
将数据导出为文本文件。
在之前的部分,我们已经将数据或输出打印到文本文件中。在本部分中,我们将导出R默认可用的整个数据集。
让我们看看它是如何工作的。 tā shì de.)
#exports the data as text file
sink('export_dataframe.txt')
airquality
sink()

您可以看到,空气质量数据集的数据被驱动到文本文件作为外部连接。
以下是如何轻松将数据在R中导入到连接中的方法。您也可以按照下面的示例将其导出为csv文件。
4. 将数据框导出到CSV文件中
在这一节中,我们将使用R中的sink()函数将数据导出到CSV文件。
让我们来看看它是如何工作的。
#export the data as csv file
sink('export_dataframe_1.csv')
iris
sink()

好吧,这是一个CSV文件,其中包含从R控制台导出的数据。R中的sink()函数提供了将数据驱动到外部连接(如文件)的最简单方法。
将数据摘要导出到连接中。
到目前为止,一切都很好。现在,让我们尝试将前面所学或理解的内容综合运用。
问题陈述很简单。
读取一个您选择的数据集,并使用summary()函数对数据进行总结。在这样做后,将结果连接到文本文件中。
让我们摇滚吧!
我们来阅读数据吧
#reads the data
df<-datasets::airquality
df
View(df)

问题陈述的第一步在这里。您可以在上面的图像中看到空气质量数据集。
2. 数据的摘要()
可以通过使用summary()函数查看数据的摘要如下。
#returns the key insights of data
summary(airquality)
Ozone Solar.R Wind Temp Month
Min. : 1.00 Min. : 7.0 Min. : 1.700 Min. :56.00 Min. :5.000
1st Qu.: 18.00 1st Qu.:115.8 1st Qu.: 7.400 1st Qu.:72.00 1st Qu.:6.000
Median : 31.50 Median :205.0 Median : 9.700 Median :79.00 Median :7.000
Mean : 42.13 Mean :185.9 Mean : 9.958 Mean :77.88 Mean :6.993
3rd Qu.: 63.25 3rd Qu.:258.8 3rd Qu.:11.500 3rd Qu.:85.00 3rd Qu.:8.000
Max. :168.00 Max. :334.0 Max. :20.700 Max. :97.00 Max. :9.000
NA's :37 NA's :7
Day
Min. : 1.0
1st Qu.: 8.0
Median :16.0
Mean :15.8
3rd Qu.:23.0
Max. :31.0
这是数据的概要,展示了最小和最大值、四分位数、中位数、平均值以及更多的洞察。
3. 将输出驱动到连接。
现在,你只需要将它导出为文本文件,并将其作为一个外部链接。
#drive the output data to txt file
sink('problem-solution.txt')
summary(airquality)
sink()

4. 断开连接
你已经完全正确地完成了所有步骤,并成功将数据驱动到了一个外部连接的文本文件中。
现在是断开连接的时候了。
#terminates the connection
unlink('problem-solution.txt')
上述命令将删除文件连接。
总结所有的步骤的话,
- Read the data in the R console.
- Apply the summary() function to the data.
- Get key insights on data.
- Drive the findings to the text file using the sink() function in R.
总结
在R中的sink()函数将R的输出驱动到外部连接,您可以将数据以多种形式导出,如文本和CSV文件。您可以将数据打印到连接中,也可以直接将全部数据导出到连接中。
在数据传输完成后,您可以取消连接来终止该文件。
R中的sink()函数以多种方式非常有用,因为它提供了临时连接来处理数据。
更多阅读:R文档