In R programming, it is very easy to import data from external files. I will show you step by step how to import files of different extensions.
But first we need to understand the file formats that are supported by R environment.
These are some common file formats that you can encounter on daily basis that are listed below:


 Supported File Formats and their Extensions

  • Comma Separated Values (.csv)
  • Tab Separated Values (.tsv)
  • SAS (.sas7bdat)
  • SPSS (.sav)
  • Stata (.dta)
  • Excel (.xls, .xlsx)
  • minitab (.mtp)
  • JSON (.json)
  • MATLAB (.mat)
  • HTML tables (.html)

There are two ways to import data in RStudio:
  • By writing one line command in R Console
  • From file option, you can directly import data
We will look into both options one by one.

The most easiest thing you can do, that work for most of the files:
  1. Open the file in Excel.
  2. Click on File menu, Save as
  3. Provide a name and select extension  '.csv'
  4. Click on OK
  5. Now your file is in csv format

Reading a Comma Separated Value file (.csv)

1. We need to set the path of file using "setwd" command.
2. Verify the path using "getwd" command.
3. Now we know our right path is set.

read csv


4. With the help of "read.csv " command , we can import the file and give the desired name to it.


read csv


5. We can see in third image that the attribute header is set to false. If it is false, then the first row of the data i.e. label will not show.


read csv


Code:
> setwd("E:/r work/boston housing")
> getwd()
>  new_data <- read.csv("boston.csv")
> head(new_data,2)
>  new_data <- read.csv("boston.csv",header = FALSE)
> head(new_data,2)

Reading JavaScript Object Notation (JSON)  files

> library("rjson")
>  new_data <- fromJSON(file = "newdata.json")

Reading Excel files

> library("readxl")
>  new_data <- read_excel("newdata.xls")
> head(new_data,2)

Reading tables

>  new_data <- read.table("newdata.txt", header=TRUE)
> head(new_data,2)

Feel free to drop a comment! 💓