在 R 中将 CSV 文件读入数据帧

借助 R 提供的特定功能,将 CSV 文件读入数据框架更容易。

什么是CSV文件?什么是CSV文件?

CSV 扩展为 Comma、Separated、Values. 在此文件中,存储的值被一个comma分开。


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

将数据存储在 Excel 表中是许多公司最常见的做法,在大多数公司中,人们将数据存储为 comma-separated-values (CSV),因为这个过程比创建正常表更容易。

作为最流行的和最强大的统计分析编程语言,R提供了从 CSV 文件中读取数据到有组织的数据框架( / 社区 / 教程 / 数据框架-in-r 编程)的特定功能。


阅读 CSV 文件到数据框架

在这个简短的示例中,我们将看到如何将 CSV 文件读成有组织的数据框架。

这个过程中的第一件事是获取并设置工作目录. 您需要选择 CSV 文件的工作路径。

1、创建工作目录

在这里,您可以使用 getwd() 函数检查默认工作目录,也可以使用 setwd() 函数更改目录。

1>getwd() #Shows the default working directory 
2
3---->   "C:/Users/Dell/Documents"
4
5> setwd("C:\Users\Dell\Documents\R-test data") #to set the new working Directory
6
7> getwd() #you can see the updated working directory
8
9---> "C:/Users/Dell/Documents/R-test data"

导入和阅读数据集 / CSV 文件

设置工作路径后,您需要导入数据集或 CSV 文件,如下所示。

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

在 R 工作室中运行上述代码行以获得如下所示的数据框架。

loading csv files in R

要检查变量readfile的类,请执行下面的代码。

1> class(readfile)
2
3---> "data.frame"

在上面的图像中,你可以看到数据框,其中包括学生的名字,他们的身份证,部门,性别和标记的信息。

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

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

为了提取学生所取得的最高分,

 1>marks <- max(data$Marks.Scored) #this will give you the highest marks
 2
 3#To extract the details of a student who scored the highest marks,
 4
 5> data <- read.csv("traindata.csv")
 6
 7> Marks <- max(data$Marks.Scored)
 8
 9> retval <- subset(data, Marks.Scored == max(Marks.Scored))   #This will
10 extract the details of the student who secured highest marks 
11
12> View(retval)

reading csv files into dataframe in R

为了提取正在化学部门学习的学生的细节,

1> readfile <- read.csv("traindata.csv")
2
3> retval <- subset( data, Department == "chemistry")  # This will extract the student details who are in Biochemistry department 
4
5> View(retval)

extracting student information from csv files in R


结论

通过此过程,您可以使用 read.csv(``)函数读取R中的csv文件,本教程涵盖如何导入 csv文件,读取 csv文件,并从数据框中提取一些特定的信息。

无论如何,您可以自由使用其他编辑器,如Thinn-R,Crimson编辑器等我希望本教程将帮助您理解R中的CSV文件的阅读和从数据框中提取一些信息。

阅读更多信息: https://cran.r-project.org/manuals.html

Published At
Categories with 技术
Tagged with
comments powered by Disqus