Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data Visualization
  • Statistics in R
  • Machine Learning in R
  • Data Science in R
  • Packages in R
  • Data Types
  • String
  • Array
  • Vector
  • Lists
  • Matrices
  • Oops in R
Open In App
Next Article:
Read contents of a CSV File in R Programming - read.csv() Function
Next article icon

Read contents of a CSV File in R Programming - read.csv() Function

Last Updated : 22 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

read.csv() function in R Language is used to read "comma separated value" files. It imports data in the form of a data frame. The read.csv() function also accepts a number of optional arguments that we can use to modify the import procedure. we can choose to treat the first row as column names, select the delimiter character, and more. For additional information on these options, consult the read.csv() documentation.

Syntax:

read.csv(file, header, sep, dec)

Parameters:

  • file: the path to the file containing the data to be imported into R.
  • header: logical value. If TRUE, read.csv() assumes that your file has a header row, so row 1 is the name of each column. If that’s not the case, you can add the argument header = FALSE.
  • sep: the field separator character.
  • dec: the character used in the file for decimal points.

Example 1: Reading File From the Same Folder 

The data variable will hold the contents of the CSV file once we have used the read.csv() function, though you are free to use another variable. Ensure that the file is in the correct CSV format with the correct delimiters and quotation characters by giving the read.csv() method the correct file path or URL. We will be using this CSV file .

R
data <- read.csv("CSVFileExample.csv",
                header = FALSE, sep = "\t")

head(data)

Output:

output1
Output

Example 2: Reading Files From Different Directories 

R
x <- read.csv("D://Datas//myfile.csv")

head(x)

Output:

output2
Output

Example 3: Reading a CSV File with a Different Delimiter

The sep option is set to ";" in this example, which indicates that the CSV file is utilizing the semicolon (;) as the delimiter rather than the standard comma (,).

R
data <- read.csv("path/to/your/file.csv", sep = ";")
head(data)

Output:

output3
Output

Example 4: Treating the First Row as Column Names

The first row of the CSV file is handled as the column names by default because the header argument is set to TRUE. If the first row of our CSV file does not contain column names, we can import the data without them by setting header = FALSE.

R
data <- read.csv("path/to/your/file.csv", header = TRUE)
head(data)

Output:

output4
Output

Example 5: Specifying Column Classes

We can define the classes for each column in the CSV file using the colClasses option. For the sake of this illustration, the first column will be interpreted as a character, the second as a number, and the third as an integer. When we want to manage the data types of particular columns.

R
data <- read.csv("path/to/your/file.csv", 
       colClasses = c("character", "numeric"))

head(data)

Output:

output5
Output

Example 6: Skipping Rows and Specifying Missing Values

We can skip a specific number of rows at the CSV file's beginning by using the skip argument. The first three rows in this illustration will be omitted. The values that should be considered as missing values (NA) are specified by the an. strings argument. The string "NA" and empty strings are both recognized as missing values in this situation.

R
data <- read.csv("path/to/your/file.csv", skip = 3, na.strings = c("", "NA"))

head(data)

Output:

output6
Output

In this article, we learned how to use the read.csv() function in R with various options to read and customize CSV file imports for effective data handling.


Next Article
Read contents of a CSV File in R Programming - read.csv() Function

N

nidhi_biet
Improve
Article Tags :
  • R Language
  • R Functions
  • R-FileHandling

Similar Reads

    Reading contents of a Text File in R Programming - read.table() Function
    The read.table() function in R can be used to read a text file's contents. A versatile and often used function for reading tabular data from different file formats, including text files, is read.table(). It returns the data in the form of a table.Syntax: read.table(filename, header = FALSE, sep = ""
    2 min read
    Read Lines from a File in R Programming - readLines() Function
    readLines() function in R Language reads text lines from an input file. The readLines() function is perfect for text files since it reads the text line by line and creates character objects for each of the lines. Syntax: readLines(path) Parameter: path: path of the file Example 1: Python3 # R progra
    2 min read
    Scan and Read Data from a File in R Programming - scan() Function
    scan() function in R Language is used to scan and read data. It is usually used to read data into vector or list or from file in R Language. Syntax: scan("data.txt", what = "character") Parameter: data.txt: Text file to be scanned Returns: Scanned output Example 1: Scanning of Text r # R Program to
    3 min read
    Reading Tabular Data from files in R Programming
    Often, the data which is to be read and worked upon is already stored in a file but is present outside the R environment. Hence, importing data into R is a mandatory task in such circumstances. The formats which are supported by R are CSV, JSON, Excel, Text, XML, etc. The majority of times, the data
    4 min read
    Reading Files in R Programming
    So far the operations using the R program are done on a prompt/terminal which is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. So the two most common o
    9 min read
    Working with CSV files in R Programming
    CSV (Comma-Separated Values) files are plain text files where each row contains data values separated by commas or other delimiters such as tabs. These files are commonly used for storing tabular data and can be easily imported and manipulated in R. We will explore how to efficiently work with CSV f
    3 min read
    How To Import Data from a File in R Programming
    The collection of facts is known as data. Data can be in different forms. To analyze data using R programming Language, data should be first imported in R which can be in different formats like txt, CSV, or any other delimiter-separated files. After importing data then manipulate, analyze, and repor
    4 min read
    How to Convert a CSV File to Microsoft Excel in R
    CSV refers to Comma-Separated Values. It holds plain text as a series of values (cells) separated by commas (, ) in a series of lines (rows). CSV file can actually open in a text editor and read it.  On the other hand, Excel is used to display the data in horizontal and vertical rows. The data are u
    2 min read
    File Handling in R Programming
    In R programming, handling files (such as reading, writing, creating, and renaming files) can be done using built-in functions available in the base R package. These operations help in managing data stored in files, which is essential for tasks like data analysis, data manipulation, and automation.
    3 min read
    How to Write Multiple Excel Files From Column Values - R programming
    A data frame is a cell-based structure comprising rows and columns belonging to the same or different data types. Each cell in the data frame is associated with a unique value, either a definite value or a missing value, indicated by NA. The data frame structure is in complete accordance with the Ex
    6 min read
top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences