Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

15. Getting Your Data into Shape > Transforming Variables

Transforming Variables

Problem

You want to transform a variable in a data frame.

Solution

Reference the new column with the $ operator, and assign some values to it. For this example, we’ll use a copy of the heightweight data set:

library(gcookbook) # For the data set
# Make a copy of the data
hw <- heightweight
hw

sex ageYear ageMonth heightIn weightLb
  f   11.92      143     56.3     85.0
  f   12.92      155     62.3    105.0
 ...
  m   13.92      167     62.0    107.5
  m   12.58      151     59.3     87.0

This will convert heightIn to centimeters and store it in a new column, heightCm:

hw$heightCm <- hw$heightIn * 2.54
hw

sex ageYear ageMonth heightIn weightLb heightCm
  f   11.92      143     56.3     85.0  143.002
  f   12.92      155     62.3    105.0  158.242
 ...
  m   13.92      167     62.0    107.5  157.480
  m   12.58      151     59.3     87.0  150.622

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint