The Base R functions are the built-in functions that are already available when you download R and RStudio. Therefore, in order to use Base R functions, you do not need to install or load any packages before using them.
Compared to the equivalent base functions, readr functions are around 10× faster. In order to use readr package functions, you need to install and load the readr package using the following commands:
install.packages(“readr”)
library(readr)
Let’s read the iris.csv file using read_csv function.
Make sure packages are loaded.
#install.packages("readr")
library(readr)
Load the csv file into a dataframe
iris <- read_csv("iris.csv")
To read in Excel data with readxl you can use the read_excel() function.
Make sure packages are loaded
#install.packages("readxl")
library(readxl)
Find existing sheets in the excel file
excel_sheets("iris.xlsx")
## [1] "iris"
Load the xlsx file into a dataframe
iris2 <- read_excel("iris.xlsx", sheet = "iris")
loading data by skipping a row
iris3 <- read_excel("iris.xlsx", sheet = "iris", skip = 1)
The foreign package provides functions that help you read data files from other statistical software such as SPSS, SAS, Stata, and others into R.
To import an SPSS data file (.sav) into R, we need to call the foreign library and then use the read.spss() function. Similarly, if we want to import a STATA data file, the corresponding function will be read.dta().
Here is an example of importing an SPSS data file.
#install.packages("foreign")
library(foreign)
Read spss data file and store it as a dataframe
iris_spss <- read.spss("iris.sav", to.data.frame = TRUE)
One of the best approaches for working with data from a database is to export the data to a text file and then import the text file into R.
Reading online .csv or .txt file is just like reading tabular data. The only difference is, we need to provide the URL of the data instead of the file name as follows:
Save the URL of the online csv file
url <- "https://data.gov.au/dataset/29128ebd-dbaa-4ff5-8b86-d9f30de56452/resource/cf663ed1-0c5e-497f-aea9-e74bfda9cf44/download/otptimeseriesweb.csv"
Use read.csv to import
ontime_data <- read.csv(url, stringsAsFactors = FALSE)