Import STATA data with haven
Next up are STATA data files; you can use read_dta()
for these.
When inspecting the result of the read_dta()
call, you will notice that one column will be imported as a labelled
vector, an R equivalent for the common data structure in other statistical environments. In order to effectively continue working on the data in R, it's best to change this data into a standard R class. To convert a variable of the class labelled
to a factor, you'll need haven
's as_factor()
function.
In this exercise, you will work with data on yearly import and export numbers of sugar, both in USD and in weight. The data can be found at: https://assets.datacamp.com/production/course_1478/datasets/trade.dta
This is a part of the course
“Intermediate Importing Data in R”
Exercise instructions
- Import the data file directly from the URL using
read_dta()
, and store it assugar
. - Print out the structure of
sugar
. TheDate
column has classlabelled
. - Convert the values in the
Date
column ofsugar
to dates, usingas.Date(as_factor(___))
. - Print out the structure of
sugar
once more. Looks better now?
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# haven is already loaded
# Import the data from the URL: sugar
# Structure of sugar
# Convert values in Date column to dates
# Structure of sugar again
This exercise is part of the course
Intermediate Importing Data in R
Parse data in any format. Whether it's flat files, statistical software, databases, or data right from the web.
Next to R, there are also other commonly used statistical software packages: SAS, STATA and SPSS. Each of them has their own file format. Learn how to use the haven and foreign packages to get them into R with remarkable ease!
Exercise 1: havenExercise 2: Import SAS data with havenExercise 3: Import STATA data with havenExercise 4: What does the graphic tell?Exercise 5: Import SPSS data with havenExercise 6: Factorize, round twoExercise 7: foreignExercise 8: Import STATA data with foreign (1)Exercise 9: Import STATA data with foreign (2)Exercise 10: Do you know your data?Exercise 11: Import SPSS data with foreign (1)Exercise 12: Excursion: CorrelationExercise 13: Import SPSS data with foreign (2)What is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.