# R code for chapter 45 manipulating cases/rows in r commander and r.r # Book details: # http://www.amazon.co.uk/Health-Science-Statistics-using-Commander/dp/190790431X # group <- c( "a","a","a","a","a","a","a","b","b","b","b","b","c","c","c","c","c") var2<- c( 3,4,6,5,6,7,6, 5,1,1,2,3, 8,9,8,7,8) test1 <-data.frame(group,var2) str(test1) # 45.1 Copying a complete dataframe newcopy <- test1 # 45.2 Copying a subset of rows (cases) a_subset <- subset(newcopy, subset=group =="a") a_subset ### also the split command - not mentioned in chapter: # use: newdataframe <- split(variable, factor variable) # e.g. newdataframe <- split(var2, group) newdataframe # produces: # $a # [1] 3 4 6 5 6 7 6 # $b # [1] 5 1 1 2 3 # $c # [1] 8 9 8 7 8 # str(newdataframe) # produces # List of 3 # $ a: num [1:7] 3 4 6 5 6 7 6 # $ b: num [1:5] 5 1 1 2 3 # $ c: num [1:5] 8 9 8 7 8 ######### # 45.3 Obtaining summary values for a subset of rows - Aggregation AggregatedData <- aggregate(test1[,c("var2"), drop=FALSE], by=list(group= test1$group), FUN=mean) AggregatedData ###### # 45.4 Correlation matrices filename <- "http://www.robin-beaumont.co.uk/virtualclassroom/book2data/computer_s_2009_rb_reduced1.dat" mydataframe <- read.delim(filename, header=TRUE) mydataframe # 45.4.1 Editing R Commander code to obtain a correlation matrix cov_matrix <- cor(mydataframe[,c("q1","q2","q3","q4","q5","q6")], use="complete.obs") cov_matrix correlations <- as.data.frame(cov_matrix) correlations ## # can conbime two above steps: correlations <- as.data.frame(cor(mydataframe[,c("q1","q2","q3","q4","q5","q6")],use="complete.obs")) correlations ## # can write the matrix to a file: write.matrix(cov_matrix, file =file.choose()) ###### end