将CSV文件读入R中的数据帧
时间:2020-02-23 14:41:42 来源:igfitidea点击:
借助R提供的特定功能,将CSV文件读入数据帧要容易得多。
什么是CSV文件?
CSV扩展为逗号,分隔符,值。
在此文件中,存储的值用逗号分隔。
这种存储数据的过程要容易得多。
为什么CSV是最常用的数据存储文件格式?
在Excel工作表中存储数据是许多中最常见的做法。
在大多数中,人们将数据存储为逗号分隔值(CSV),因为此过程比创建普通电子表格容易。
之后,他们可以使用R的内置程序包读取和分析数据。
作为最流行和功能最强大的统计分析编程语言,R提供了特定的功能以将数据从CSV文件读入组织的数据帧中。
将CSV文件读取到数据框
在这个简短的示例中,我们将看到如何将CSV文件读取为有组织的数据帧。
此过程中的第一件事是获取并设置工作目录。
您需要选择CSV文件的工作路径。
1.设置工作目录
其中您可以使用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中执行上述代码行以获取数据框架,如下所示。
要检查变量" readfile"的类,请执行以下代码。
> class(readfile) ---> "data.frame"
在上图中,您可以看到数据框,其中包含学生姓名,学生的ID,部门,性别和标记的信息。
3.从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)
要提取正在"化学"系学习的学生的详细信息,
> readfile <- read.csv("traindata.csv") > retval <- subset( data, Department == "chemistry") # This will extract the student details who are in Biochemistry department > View(retval)