When importing from a command, a csv file can be imported using the function read.csv().
The general structure of read.csv is
data_frame_name_in_R <- read.csv('path/of/file/name', header = TRUE)
Please Note: there are specific types of functions available for different file formats.
Suppose we have a csv file in our P drive, so we would do the following to import it.
df <- read.csv('P:/r_tutorial/NHS-99M001X-E-2011-pumf-individuals_F1.csv', header = TRUE)
# the data is stored in data frame named df
NOTE: make sure to keep forward slashes (/) in the pathname.
The CSV is imported as a df – data frame
R can be used to import a wide variety of files from csv to json. For this guide, we will be importing a csv file and working on it.
Files can be imported by GUI in R Studio. Follow the steps below.
A dialog box will appear. Browse to the csv dataset.
Select it and click on “Open” and then “Import”.
You can also import an SPSS data file (.sav) in R, using the read.spss() command.
Firstly, make sure that you have loaded the "foreign" package.
> library(foreign)
Then you can use the read.spss command as shown below:
>df <- read.spss('C:/Users/owner/Downloads/NHS-99M001X-E-2011-pumf-individuals/NHS-99M001X-E-2011-pumf-individuals_F1.sav', use.value.labels = TRUE, to.data.frame = TRUE)
Here we have 2 extra parameters apart from the first one, which is the location of the .sav file.
"use.value.labels" is set to TRUE if you want to retain the value labels.
"to.data.frame" is set to TRUE, if it is FALSE (default), the df would be a list instead of a data frame.
For a list of all the parameters for this function, please refer to: https://stat.ethz.ch/R-manual/R-devel/library/foreign/html/read.spss.html
You can also import a STATA data file (.dta) in R, using the read.dta() command.
Firstly, make sure that you have loaded the "foreign" package.
> library(foreign)
Then you can use the read.dta command as shown below:
> mydata <- read.dta('C:/Users/owner/Downloads/NHS-99M001X-E-2011-pumf-individuals/NHS-99M001X-E-2011-pumf-individuals_F1.dta')
For a list of all the parameters for this function, please refer to: https://stat.ethz.ch/R-manual/R-devel/library/foreign/html/read.dta.html
McGill Libraries • Questions? Ask us!
Privacy notice