Created
April 16, 2012 20:45
-
-
Save geofferyzh/2401403 to your computer and use it in GitHub Desktop.
RinAction - R Data Manipulation - Creating New Variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-----------------------------------------------------------------------------# | |
#-----------------------------------------------------------------------------# | |
# R in Action - Data Management # | |
#-----------------------------------------------------------------------------# | |
#-----------------------------------------------------------------------------# | |
install.packages(c('reshape', 'sqldf')) | |
# Create the data frame | |
manager <- c(1, 2, 3, 4, 5) | |
date <- c("10/24/08", "10/28/08", "10/1/08", "10/12/08", "5/1/09") | |
gender <- c("M", "F", "F", "M", "F") | |
age <- c(32, 45, 25, 39, 99) | |
q1 <- c(5, 3, 3, 3, 2) | |
q2 <- c(4, 5, 5, 3, 2) | |
q3 <- c(5, 2, 5, 4, 1) | |
q4 <- c(5, 5, 5, NA, 2) | |
q5 <- c(5, 5, 2, NA, 1) | |
leadership <- data.frame(manager, date, gender, age, q1, q2, q3, q4, q5, stringsAsFactors = FALSE) | |
# the individual vectors are no longer needed | |
rm(manager, date, gender, age, q1, q2, q3, q4, q5) | |
################################################# | |
## Creating new variables ## | |
## - in the same data frame ## | |
################################################# | |
# Method 1 --> create new vectors | |
mydata <- data.frame(x1 = c(2, 2, 6, 4), x2 = c(3,4, 2, 8)) | |
mydata$sumx <- mydata$x1 + mydata$x2 | |
mydata$meanx <- (mydata$x1 + mydata$x2)/2 | |
# method 2 --> Using Attach/Detach | |
attach(mydata) | |
mydata$sumx <- x1 + x2 | |
mydata$meanx <- (x1 + x2)/2 | |
detach(mydata) | |
# Method 3 --> Using Transform() function | |
mydata <- transform(mydata, sumx = x1 + x2, meanx = (x1 + x2)/2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment