Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R read.csv() Function - Reading CSV Files

R read.csv() Function - Reading CSV Files

R Language Examples R Language Examples

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:

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"

)

print

(

"CSV data read:"

)

print

(

data

)

View the structure

print

(

"Data types:"

)

print

(

str

(

data

)

)

Specify options when reading

data2

<-

read.csv

(

"temp_students.csv"

,

                  stringsAsFactors

=

FALSE

)

print

(

"Strings converted to factors:"

)

print

(

str

(

data2

)

)

The output of the code above is:

[1] "读取的 CSV 数据:"

  姓名 年龄 成绩

1 张三   25   88

2 李四   30   92

3 王五   28   76

R Language Examples R Language Examples