How to import data from STATA to R Studio

Today we are going to talk about importing data from .dta format to R studio

First step is to install and load the foreign package

library(foreign)

We need to know the current wokring directory

getwd()
## [1] "C:/Users/aamir/Box/Youtube Channel/R sessions/04. How to import data to from STATA to R Studio"

File that is needed to be imported is needed to be coppied to the current working directory.

We need to use read.dta function, specify the name of the file from the current working directory

mydata <- read.dta("autornd.dta")

Now we can see the number of variables in this dataset

str(mydata)
## 'data.frame':    74 obs. of  3 variables:
##  $ make  : chr  "AMC Concord" "AMC Pacer" "AMC Spirit" "Buick Century" ...
##  $ weight: num  3000 3500 2500 3500 4000 3500 2000 3500 4000 3500 ...
##  $ mpg   : num  20 15 20 20 15 20 25 20 15 20 ...
##  - attr(*, "datalabel")= chr "1978 Automobile Data"
##  - attr(*, "time.stamp")= chr " 2 Apr 2005 09:54"
##  - attr(*, "formats")= chr  "%-18s" "%9.0g" "%9.0g"
##  - attr(*, "types")= int  18 254 254
##  - attr(*, "val.labels")= chr  "" "" ""
##  - attr(*, "var.labels")= chr  "Make and Model" "Weight (lbs.)" "Mileage (mpg)"
##  - attr(*, "expansion.fields")=List of 4
##   ..$ : chr  "_dta" "note1" "produced from auto.dta"
##   ..$ : chr  "_dta" "note2" "mpg rounded to 5 mpg increments"
##   ..$ : chr  "_dta" "note0" "3"
##   ..$ : chr  "_dta" "note3" "weight rounded to 500 lb increments"
##  - attr(*, "version")= int 8

In addition to this we can also see the first six rows of this dataset with the head function

head(mydata)
##            make weight mpg
## 1   AMC Concord   3000  20
## 2     AMC Pacer   3500  15
## 3    AMC Spirit   2500  20
## 4 Buick Century   3500  20
## 5 Buick Electra   4000  15
## 6 Buick LeSabre   3500  20