1. Learn
  2. /
  3. Courses
  4. /
  5. Reading Data into R with readr

Exercise

Coercing columns to different data types

The import functions in readr are quite good at guessing the correct data type for each column in a dataset. Of course, they aren't perfect, so sometimes you will need to change the type of a column after importing.

You might also find that the way your data are encoded prevents readr from assigning them the desired types. If your dataset stores dates like August 12, 2016 as 20160812, they will of course be read in as integers. In this situation, you could then insert dashes at the appropriate locations and call type_convert() to ask readr to try parsing again.

In this exercise, you'll be calling type_convert() using a column specification you create. This is a manual override and should not be needed often. To create the column specification, you'll use cols() as follows:

# Convert each column to specified type
# i for int, d for double, etc.
new_df <- type_convert(df, 
            col_types = cols(col1 = "d", 
                             col2 = "i",
                             ...
            ))

Instructions

100 XP

Use type_convert() to change all columns of trees (Girth, Height, and Volume) to doubles. Assign the resulting data frame to trees2.