在R中将CSV文件读入数据框架中

在R提供的特定功能的帮助下,将CSV文件读入数据框变得更加简单。

CSV文件是什么?

CSV被扩展为逗号分隔值。在这个文件中,存储的数值是用逗号分隔的。这种数据存储的过程更加便捷。


为什么CSV是最常用的数据存储文件格式?

在许多公司中,将数据存储在Excel表中是最常见的做法。在大多数公司,人们将数据存储为逗号分隔值(CSV),因为这个过程比创建普通电子表格容易。随后,他们可以使用R的内置包来读取和分析数据。

作为最受欢迎和功能强大的统计分析编程语言,R提供了特定的函数,可以从CSV文件中读取数据并组织为数据框架。


读取 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"

2. 导入并读取数据集/CSV文件

在设定好工作路径之后,您需要按照以下所示的方式导入数据集或CSV文件。

> readfile <- read.csv("testdata.txt")

在R Studio中执行上述代码以获得如下所示的数据框。

loading csv files in R

执行以下代码以检查变量’readfile’的类型。

> class(readfile)

---> "data.frame"            

在上面的图像中,您可以看到数据框,其中包含学生姓名、ID、系别、性别和成绩的信息。

从CSV文件中提取学生的信息

在获得数据框之后,现在可以对数据进行分析。您可以从数据框中提取特定的信息。

抽取学生取得的最高分

>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)

reading csv files into dataframe in R

提取正在学习化学系的学生的详细信息。

> readfile <- read.csv("traindata.csv")

> retval <- subset( data, Department == "chemistry")  # This will extract the student details who are in Biochemistry department 
 
> View(retval)

extracting student information from csv files in R

结论

通过使用read.csv(“”)函数,您可以使用此过程在R中读取csv文件。本教程介绍了如何导入csv文件、读取csv文件以及从数据框中提取一些特定信息。

我在这个项目中使用了R Studio。RStudio提供了很棒的功能,例如控制台、编辑器和环境等等。当然,你也可以自由选择其他编辑器,比如Thinn-R、Crimson editor等等。我希望这个教程能够帮助你理解如何在R中读取CSV文件并从数据框中提取一些信息。

更多阅读请参考:https://cran.r-project.org/manuals.html

发表回复 0

Your email address will not be published. Required fields are marked *