How To Create A Dataframe In R From CSV

In this tutorial, you’ll learn how to create a dataframe in R from a CSV file. A dataframe is a two-dimensional tabular data structure widely used to store and manipulate data in R.

The CSV (Comma Separated Values) format is helpful for organizing and storing datasets. By importing a CSV file into R as a dataframe, you can take advantage of R’s powerful data manipulation and analysis capabilities.

Step 1: Install and Load Required Packages

To work with CSV files in R, you’ll need to install and load the required packages. You need the “readr” package for reading CSV files. Install the package (if not already installed) and load it using the following commands:

Step 2: Download and Prepare the CSV File

Download the sample CSV file and save it to your computer. For the purpose of this tutorial, we’ll use a dataset containing information about cars named Auto MPG. Here are the first few lines of the sample file:

"chevrolet chevelle malibu";18;8;307;130;3504;12;70;US
"buick skylark 320";15;8;350;165;3693;11.5;70;US
"plymouth satellite";18;8;318;150;3436;11;70;US
"amc rebel sst";16;8;304;150;3433;12;70;US

Note that the dataset uses a semicolon (;) as a delimiter instead of a comma (,). If your dataset uses commas, you can skip Step 3.

Step 3: Modify Delimiter (If Necessary)

If your CSV file uses a delimiter other than a comma, you need to modify the read_csv function to accommodate the change. In our example dataset, the delimiter is “;”:

Replace “path/to/your/file” with the actual path of the dataset saved on your computer.

Step 4: Verify the Dataframe

To ensure that the data is imported correctly, view the first few rows of the dataframe using the head() function:

You should see the data is successfully imported as a dataframe. Now you can proceed to analyze and manipulate the data using R’s functions.

Full Code:

Here’s the complete code for creating a dataframe in R from a CSV file:


In this tutorial, you learned how to create a dataframe from a CSV file in R using the readr package. This helps you import data from external sources for analysis and manipulation purposes. Now you can continue to work with your data using R’s powerful data processing and visualization tools.