R read.csv() Function - Read CSV Files

R 语言实例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, and 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:

  • fileFile path or URL.

  • headerWhether the first row is used as column names, default TRUE.

  • sepSeparator, defaults to comma for csv. read.csv2() uses semicolon.

  • stringsAsFactorsWhether to convert strings to factors, defaulting to FALSE 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")
print("Read CSV data:")
print(data)

# View 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))

Executing the above code produces the following output:

[1] "读取的 CSV 数据:"
  姓名 年龄 成绩
1 张三   25   88
2 李四   30   92
3 王五   28   76

R 语言实例R Language Examples

Other Extensions