# R code for chapter 44 manipulating variables (columns) in R Commander and R # Book details: # Health Science Statistics using R and R Commander # by Robin Beaumont # Paperback - ISBN 9781907904318 # http://www.amazon.co.uk/Health-Science-Statistics-using-Commander/dp/190790431X # or direct from publisher at: # http://www.scionpublishing.com/ # book website: http://www.robin-beaumont.co.uk/rbook ########################################################### # var1<- c(2,4,3,5,6,5,6,4,NA,1) var2<- c(2,5,4,5,6,2,3,4,NA,3) mydataframe <- data.frame(var1, var2) # Recoding a variable, changing all 5's to 10's: # into a new factor mydataframe$newvar <- Recode(mydataframe$var1, '5 =10', as.factor.result=TRUE) # into a new variable NOT a factor: mydataframe$newvar <- Recode(mydataframe$var1, '5 =10', as.factor.result=FALSE) # changing the values in a variable to a calculated value mydataframe$var1_squared <- with(mydataframe, var1^2) # creating standardised variables: # a single variable: mydataframe$Zvar1 <- scale(mydataframe$var1) # if you have a dataframe with only numeric variables you can allpy the # scale() function to it en masse otherwise you get an error: newdata_scaled <- scale(mydataframe) # 1.4 Converting numeric variable(s) to factors with level values # converting a variable to a factor: mydataframe$var1factor <- as.factor(mydataframe$var1) mydataframe # 1.5 Converting numeric variable(s) to factors with level names mydataframe$var1factor2 <- factor(mydataframe$var1, labels=c('red','yellow','green','blue','brown','black')) # 1.6 Which of my variables are factors? str(mydataframe) # 1.7 Converting and grouping a numeric variable to a factor with level values: 'binning' # 1.8 Reorder factor levels mydataframe$var1factor_reorder <- factor(mydataframe$var1factor, levels=c('2','1','3','4','6','5')) mydataframe$var1factor_ordered <- factor(mydataframe$var1factor, levels=c('2','1','3','4','6','5'), ordered=TRUE) # 1.9 Renaming one or more variables names(mydataframe)[c(4,6)] <- c("squared","factored") # 1.10 Deleting one or more variables mydataframe$var1factor_ordered <- NULL ##### end