R CSV Files: Read, Process, Filter, and Write CSV Data

CSV files are one of the most common formats for moving tabular data between spreadsheets, databases, and R programs. In R, a CSV file is usually read into a data.frame, processed with normal data frame operations, and written back to another CSV file when the analysis result has to be saved.

In this R tutorial, you will learn how to read CSV files in R, inspect the imported data, filter records, handle common import options, and write the processed data to a new CSV file.

Example of a CSV File, that we use in the examples going forward, is given below :

</>
Copy
Andrew,28,25.2
Mathew,23,10.5
Dany,49,11
Philip,29,21.9
John,38,44
Bing,23,11.5
Monica,29,45

The rows above show the comma-separated structure. For the examples in this tutorial to produce columns named name, age, and income, save the complete file as sampleCSV.csv with a header row as shown below.

</>
Copy
name,age,income
Andrew,28,25.2
Adarsh,23,10.5
Dany,49,11
Philip,29,21.9
John,38,44
Bing,23,11.5
Monica,29,45

You may refer R Working Directory to modify the path of R Workspace to point to the directory containing your input files (CSV Files).

Read CSV Files in R Using read.csv()

CSV Files are those files with values separated by commas in each row. Each row corresponds to a record or observation.

In base R, the most direct function for importing a comma-separated file is read.csv(). By default, read.csv() treats the first row as column names, uses comma as the separator, and returns a data frame. For the full set of arguments, you can also refer to the official R documentation for read.table and read.csv.

The syntax of function to read CSV File in R programming language is

</>
Copy
read.csv(<filename>)

A practical read.csv() call often includes options for headers, missing values, and text encoding. For example:

</>
Copy
csvData <- read.csv(
  "sampleCSV.csv",
  header = TRUE,
  stringsAsFactors = FALSE,
  na.strings = c("", "NA")
)

Here, header = TRUE tells R that the first row contains column names. The na.strings argument converts blank fields and NA text values into missing values in R.

Example 1 – Read CSV File in R

In this example, we will read a CSV File using read.csv() function.

r_readCSVexample.R

</>
Copy
# Example R program to read CSV File
#set working directory - the directory containing csv file
setwd("/home/arjun/workspace/r")
#read csv file
csvData = read.csv("sampleCSV.csv")
# print the data type of csvData 
cat("CSV Data type : ",class(csvData), "\n\n")
print(csvData)

Output

$ Rscript r_readCSVexample.R 
CSV Data type :  data.frame 
    name age income
1 Andrew  28   25.2
2 Adarsh  23   10.5
3   Dany  49   11.0
4 Philip  29   21.9
5   John  38   44.0
6   Bing  23   11.5
7 Monica  29   45.0

Please observe that the data of csv file is read to an R Data Frame.

Check Imported CSV Column Names and Data Types in R

After reading a CSV file, always check the structure before filtering or calculating values. This helps you confirm whether numeric columns were imported as numbers and whether the expected column names are available.

</>
Copy
str(csvData)
names(csvData)
summary(csvData)

If a numeric column is imported as character data, check whether the CSV has currency symbols, commas inside numbers, spaces, or non-numeric text in that column.

Process CSV Data in R After Import

R programming language reads the CSV File to an R Data frame. So, you may use all the R Data Frame functions to process the data.

Common processing steps after importing CSV data include selecting columns, filtering rows, sorting records, calculating summaries, and removing incomplete rows. The next example filters the rows where the income value is equal to the maximum income in the file.

Example 2 – Process CSV Data in R

In this example, we will read a CSV File and then process this data. We will extract rows, whose income is equal to the maximum of income.

r_csv_analyze_data.R

</>
Copy
# Example R program to analyze CSV File
#set working directory - the directory containing csv file
setwd("/home/arjun/workspace/r")
#read csv file
celebrities = read.csv("sampleCSV.csv")
# retrieve rows based on a condition
maxSalariedCelebrities = subset(celebrities, income==max(income))
# print the result
print(maxSalariedCelebrities)

Output

$ Rscript r_csv_analyze_data.R 
    name age income
7 Monica  29     45

Filter CSV Rows in R with Multiple Conditions

You can also filter CSV data using more than one condition. The following example selects rows where age is greater than or equal to 28 and income is greater than 20.

</>
Copy
filteredCelebrities <- subset(celebrities, age >= 28 & income > 20)

print(filteredCelebrities)
    name age income
1 Andrew  28   25.2
4 Philip  29   21.9
5   John  38   44.0
7 Monica  29   45.0

When filtering CSV rows in R, make sure the column names used in the condition match the names in the imported data frame exactly.

Write transformed data to CSV Files

Once we extract the required data or transform the data which is in data frame, we may write data frame to a CSV File.

The base R function for exporting a data frame to a CSV file is write.csv(). It creates a comma-separated file that can be opened again in R or in spreadsheet software. In many cases, you may want to add row.names = FALSE so that R does not write row numbers as an extra first column.

</>
Copy
write.csv(data_frame, "output-file.csv", row.names = FALSE)

Example 3 – Write Transformed Data to CSV in R

In this example, we will extract the rows with maximum income, and write these rows to a CSV File.

r_csv_write_data.R

</>
Copy
# Example R program to write data to a CSV file
#set working directory - the directory containing csv file
setwd("/home/arjun/workspace/r")
#read csv file
celebrities = read.csv("sampleCSV.csv")
# retrieve rows based on a condition
maxSalariedCelebrities = subset(celebrities, income==max(income))
# write filtered data into a new CSV file.
write.csv(maxSalariedCelebrities,"result.csv")

Output

$ Rscript r_csv_write_data.R 
R CSV Files - Read CSV File using R - Write to CSV File in R

If you do not want the row index column in the exported CSV file, use the following form.

</>
Copy
write.csv(maxSalariedCelebrities, "result.csv", row.names = FALSE)

Read Multiple CSV Files in R from One Folder

When a folder contains several CSV files with the same columns, you can read all of them and combine them into one data frame. This is useful when data is split by day, month, region, or report type.

</>
Copy
csvFiles <- list.files(
  path = "/home/arjun/workspace/r",
  pattern = "\\.csv$",
  full.names = TRUE
)

csvList <- lapply(csvFiles, read.csv)
combinedCsvData <- do.call(rbind, csvList)

print(combinedCsvData)

This approach works best when every CSV file has the same column names and compatible data types. If the files have different structures, inspect each file before combining them.

Why R May Not Read a CSV File Correctly

If R is not reading a CSV file as expected, the problem is usually related to the file path, delimiter, header row, encoding, or inconsistent data values.

Problem while reading CSV in RLikely reasonPractical fix
File not found errorR is looking in a different working directoryUse getwd(), set the correct working directory, or pass the full file path
First data row becomes column namesThe CSV file has no header rowUse header = FALSE and assign column names manually
All values appear in one columnThe file is not comma-separatedUse read.csv2() or read.table() with the correct sep value
Numbers are imported as textNumbers contain symbols, extra spaces, or formatting charactersClean the column values and convert them using numeric conversion functions
Special characters display incorrectlyText encoding mismatchTry an appropriate fileEncoding value while reading the file

R CSV Import and Export Checklist

  • Confirm that sampleCSV.csv is saved in the folder where R is reading files, or use the full file path.
  • Check whether the CSV file has a header row before using the default read.csv() settings.
  • Run str() after import to verify that numeric columns such as age and income were imported with the expected data types.
  • Use row.names = FALSE in write.csv() when the exported file should not contain R row numbers.
  • Open the exported CSV file and verify that filtered rows and column names match the intended result.

FAQs on Reading and Writing CSV Files in R

How do I read and write a CSV file in R?

Use read.csv("file.csv") to read a CSV file into a data frame. After processing the data frame, use write.csv(dataFrame, "output.csv", row.names = FALSE) to write the result to a new CSV file.

Can R read CSV files without installing extra packages?

Yes. Base R includes read.csv() for reading CSV files and write.csv() for writing CSV files. Extra packages are optional and are usually used for larger workflows or different syntax preferences.

Why is R not reading my CSV file?

Common reasons include an incorrect working directory, a wrong file name, missing file extension, a CSV file without a header row, a delimiter that is not a comma, or a text encoding issue. Start by checking getwd(), the file path, and the first few lines of the CSV file.

How do I read a CSV file in R without column headers?

Use read.csv("file.csv", header = FALSE). You can then assign names with names(dataFrame) <- c("column1", "column2"), using the actual column names required for your data.

How do I stop write.csv() from adding row numbers?

Add row.names = FALSE to the export call. For example, use write.csv(resultData, "result.csv", row.names = FALSE).

Conclusion: Read, Filter, and Save CSV Data in R

In this R Tutorial – R CSV Files, we have learnt to read CSV File using R, process data read from CSV using R and write process data to CSV using R.

The usual workflow is simple: keep the CSV file in the correct location, import it with read.csv(), inspect the resulting data frame, process or filter the rows, and save the result with write.csv(). Checking headers, data types, and exported row names helps avoid most beginner CSV issues in R.