R read.csv() Function - Reading CSV Files
The R read.csv() function is used to read CSV (comma-separated values) files into a data frame.
It is the first step in data analysis; CSV is the most common data exchange format.
The syntax of the read.csv() function is as follows:
read.csv(file, header = TRUE, sep = ",", stringsAsFactors = FALSE)
Parameter Description:
-
file A file path or URL.
-
header Whether the first row is used as column names, TRUE by default.
-
sep The separator; csv uses a comma by default. read.csv2() uses a semicolon.
-
stringsAsFactors Whether to convert strings to factors; FALSE by default since R 4.0.
Example
First create a sample CSV file
df
<-
data.frame
(
Name
=
c
(
"Zhang San"
,
"Li Si"
,
"Wang Wu"
)
,
Age
=
c
(
25
,
30
,
28
)
,
Score
=
c
(
88
,
92
,
76
)
)
write.csv
(
df
,
"temp_students.csv"
,
row.names
=
FALSE
)
Read the CSV file
data
<-
read.csv
(
"temp_students.csv"
)
(
"CSV data read:"
)
(
data
)
View the structure
(
"Data types:"
)
(
str
(
data
)
)
Specify options when reading
data2
<-
read.csv
(
"temp_students.csv"
,
stringsAsFactors
=
FALSE
)
(
"Strings converted to factors:"
)
(
str
(
data2
)
)
The output of the code above is:
[1] "读取的 CSV 数据:"
姓名 年龄 成绩
1 张三 25 88
2 李四 30 92
3 王五 28 76
R Language Examples