#======================================================== # R script to read text file containing college GPA data # into a data frame, extract the males-only data, and # store the males-only data in a separate text file. The # input file should have data elements separated on lines # by spaces, tabs, or commas. #======================================================== #-------------------------------------------------------- # 1. Designate the working folder where R is to find # and write the data. User must substitute the appropriate # directory and file name between the quotes. #----------------------------------------------------------- # setwd("c:/myname/myRfolder") # Precede any spaces in # folder or file names with # backslash, for example: # setwd("c:/myname/my\ R\ folder") #----------------------------------------------------------- # 2. Read the data in the text file into an R data frame # named GPA.data. The header=TRUE statement tells R that # the first line of the text file contains column or variable # names. The sep=" " option tells R that spaces separate # data elements in lines of the text file. #----------------------------------------------------------- GPA.data=read.table("GPAdata.txt",header=TRUE,sep=" ") # Use header=FALSE if # the first line of the # data file does not # contain column names. #----------------------------------------------------------- # 3. Attach the data frame, making the columns available in R # as vectors. #----------------------------------------------------------- attach(GPA.data) GPA.data #----------------------------------------------------------- # 4. Extract the males-only data from the vectors. (Also # perform on the data whatever analyses are desired.) #----------------------------------------------------------- univGPA.male=univGPA[sex=="m"] ACT.male=ACT[sex=="m"] hsGPA.male=hsGPA[sex=="m"] housing.male=housing[sex=="m"] #----------------------------------------------------------- # 5. Gather the males-only vectors into a separate data # frame. #----------------------------------------------------------- GPA.data.male=data.frame(univGPA.male,ACT.male,hsGPA.male, housing.male) #----------------------------------------------------------- # 6. Store the males-only data in a text file in the current # working folder. Data values in each line will be separated # by whatever text character designated in the sep=" " argument. # Print the males-only data in the console just by typing the # name of the data frame. #----------------------------------------------------------- write.table(GPA.data.male,file="GPAdata_male.txt",sep=" ") GPA.data.male #----------------------------------------------------------- # 7. Detach the data frame, removing the vectors from # workspace, if further analyses with different data are to be # performed in the R session. #----------------------------------------------------------- detach(GPA.data)