将 CSV 文件读入 R 中的数据帧
在本文中,我们将学习如何使用 R 编程语言将 CSV 文件导入或读取到数据帧中。
使用中的数据集:
第 1 步:设置或更改工作目录
为了将给定的 CSV 文件导入或读取到我们的数据框中,我们首先需要检查我们当前的工作目录,并确保 CSV 文件与我们的 R Studio 位于同一目录中,否则它可能会显示“未找到文件错误”。
要检查当前工作目录,我们需要使用 getwd()函数,要将当前工作目录更改为其他工作目录,我们需要使用steved()函数。
getwd() 返回表示 R 进程当前工作目录的绝对文件路径。
句法:
getwd()
setwd(dir) 用于将工作目录设置为 dir。
句法:
setwd(path)
例子:
R
# gives the current working directory
getwd()
# changes the location
setwd("C:/Users/Vanshi/Desktop/gfg")
R
sdata <- read.csv("SampleData.csv", header = TRUE, sep = ",")
sdata
# views the data frame formed from the csv file
View(sdata)
R
sdata <- read.csv(
"SampleData.csv", header = TRUE, sep = ",")
highspeed <- subset(
sdata, sdata$speed == max(sdata$speed))
# views the subsetted value in
# tabular form
View(highspeed)
R
sdata <- read.csv(
"SampleData.csv", header = TRUE, sep = ",")
highfreq <- subset(
sdata, sdata$cyc_freq == "Several times per week")
# views the information, of the above
# condition in tabular format
View(highfreq)
输出:
C:/Users/Vanshi/Documents
第 2 步:读取 CSV 文件
现在我们已经设置了我们的工作路径,我们将把 CSV 文件导入到数据框中,并将我们的数据框命名为 sdata。
在这里,我们使用 read.csv 命令将名为“SampleData”的 .csv 文件读入我们的 R studio,这意味着我们将这些值提供给 Rstudio 以从中提取一些重要信息。
read.csv()函数读取表格格式的文件并从中创建数据框,案例对应于文件中的行和变量到字段。
Syntax: read.csv(file, header = TRUE, sep = “,”, quote = “\””, dec = “.”, fill = TRUE, comment.char = “”, …)
Arguments:
- file: the name of the file which the data are to be read from.
- header: a logical value indicating whether the file contains the names of the variables as its first line. If missing, the value is determined from the file format: header is set to TRUE if and only if the first row contains one fewer field than the number of columns.
- sep: the field separator character. Values on each line of the file are separated by this character. If sep = “” (the default for read.table) the separator is ‘white space’, that is one or more spaces, tabs, newlines or carriage returns.
- quote: the set of quoting characters.
- dec: the character used in the file for decimal points.
- fill: logical. If TRUE then in case the rows have unequal length, blank fields are implicitly added.
- comment.char: character: a character vector of length one containing a single character or an empty string.
- … : Further arguments to be passed.
例子:
电阻
sdata <- read.csv("SampleData.csv", header = TRUE, sep = ",")
sdata
# views the data frame formed from the csv file
View(sdata)
输出:
现在,我们已经创建了我们的数据框,我们可以对其执行一些操作。根据使用情况从数据框中读取的数据。下面给出了两个根据他们的要求读取数据的例子。
示例 1:
电阻
sdata <- read.csv(
"SampleData.csv", header = TRUE, sep = ",")
highspeed <- subset(
sdata, sdata$speed == max(sdata$speed))
# views the subsetted value in
# tabular form
View(highspeed)
输出:
示例 2:
电阻
sdata <- read.csv(
"SampleData.csv", header = TRUE, sep = ",")
highfreq <- subset(
sdata, sdata$cyc_freq == "Several times per week")
# views the information, of the above
# condition in tabular format
View(highfreq)
输出: