借助 R 提供的特定函数,将 CSV 文件读入数据帧要容易得多。
CSV 扩展为逗号、分隔、值。在此文件中,存储的值用逗号分隔。存储数据的过程要容易得多。
将数据存储在 Excel 工作表中是许多公司最常见的做法。在大多数公司中,人们将数据存储为逗号分隔值 (CSV),因为该过程比创建普通电子表格更容易。之后他们可以使用 R 的内置包来读取和分析数据。
作为最流行和最强大的统计分析编程语言,R 提供了将数据读取为有组织的特定函数数据框来自 CSV 文件。
在这个简短的示例中,我们将了解如何将 CSV 文件读入有组织的数据帧中。
此过程中的第一件事是获取并设置工作目录。您需要选择 CSV 文件的工作路径。
在这里,您可以使用 getwd() 函数检查默认工作目录,也可以使用函数 setwd() 更改目录。
>getwd() #Shows the default working directory
----> "C:/Users/Dell/Documents"
> setwd("C:\Users\Dell\Documents\R-test data") #to set the new working Directory
> getwd() #you can see the updated working directory
---> "C:/Users/Dell/Documents/R-test data"
设置工作路径后,需要导入数据集或CSV文件,如下所示。
> readfile <- read.csv("testdata.txt")
在R studio中执行上面这行代码,得到如下所示的数据帧。
要检查变量“readfile”的类,请执行以下代码。
> class(readfile)
---> "data.frame"
在上图中,您可以看到数据框,其中包括学生姓名、ID、部门、性别和分数信息。
获取数据框后,您现在可以分析数据。您可以从数据框中提取特定信息。
为了提取学生的最高分,
>marks <- max(data$Marks.Scored) #this will give you the highest marks
#To extract the details of a student who scored the highest marks,
> data <- read.csv("traindata.csv")
> Marks <- max(data$Marks.Scored)
> retval <- subset(data, Marks.Scored == max(Marks.Scored)) #This will
extract the details of the student who secured highest marks
> View(retval)
提取在“化学”系学习的学生的详细信息,
> readfile <- read.csv("traindata.csv")
> retval <- subset( data, Department == "chemistry") # This will extract the student details who are in Biochemistry department
> View(retval)
通过此过程,您可以使用 read.csv(“ “) 函数读取 R 中的 csv 文件。本教程介绍如何导入 csv 文件、读取 csv 文件以及从数据框中提取一些特定信息。
我在这个项目中使用了 R studio。 RStudio 还提供控制台、编辑器和环境等出色的功能。无论如何,您可以自由地使用其他编辑器,例如 Thinn-R、Crimson 编辑器等。我希望本教程能够帮助您了解 R 中 CSV 文件的读取并从数据框中提取一些信息。
更多内容请阅读:https://cran.r-project.org/manuals.html