######################### # # # # # Homework 3 Solutions # # # # # ######################### ##Question 1: Create dataframe "ageweight" age=c(5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80) weight=c(30, 55, 105, 110, 115, 140, 190, 170, 120, 128, 165, 132, 174, 201, 133, 164) ageweight=data.frame(age,weight) attach(ageweight) ##Create newage function newage<-function(age){ ifelse(age<=20,1,ifelse(age>50,3,2)) } ##apply newage function to the age variable in the ageweight dataset age_cat<-newage(ageweight\$age) #Question 2 ##A: Read in the fram_heart dataset fram_heart<-read.csv("/Users/Avery/Desktop/classes/720 Intro to R/summer 2014/wk3/fram_heart.csv") ##B: Use the help command to find information on the replace function ?help #C: Use a loop to replace missing values with "." There are multiple ways to do this, here are a few. #in my opinion, this is the easiest way: for (i in 1:ncol(fram_heart)){ missing<-which(fram_heart[,i]==999 |fram_heart[,i]==-99|fram_heart[,i]==-9) fram_heart[,i]<-replace(fram_heart[,i], missing, ".") print(i) } for (i in 1:nrow(fram_heart)) {   if (fram_heart\$dia[i] == 999)     replace(fram_heart\$dia, i, ".")     if (fram_heart\$mi[i] == 999)     replace(fram_heart\$mi, i, ".")     if (fram_heart\$weight[i] == -99)     replace(fram_heart\$weight, i, ".")     if (fram_heart\$height[i] == -9)     replace(fram_heart\$height, i, ".")   } n=nrow(fram_heart) ##12,13,7,9 fram_heart_new<-c() for (i in 1:ncol(fram_heart)){ missing<-which(fram_heart[,i]==999 |fram_heart[,i]==-99|fram_heart[,i]==-9) new_column<-replace(fram_heart[,i], missing, ".") fram_heart_new<-cbind(fram_heart_new,new_column) print(i) } colnames(fram_heart_new)<-colnames(fram_heart) fhs<-as.data.frame(fram_heart_new) for(j in c(2,12,13)){ fhs[,j]=as.numeric(fhs[,j]) } for(i in 1:nrow(fram_heart)) for(j in 1:ncol(fram_heart)) fram1<-if(fram_heart[i,j] == 999 | fram_heart[i,j] == -99 | fram_heart[i,j] == -9) fram_heart[i,j] <- "." numcol=ncol(Fram_heart) numrow=nrow(Fram_heart) for (j in 1:numrow) for(i in 1:numcol) fram_heartnew=if (Fram_heart[j,i] == -99||Fram_heart[j,i] == -9||Fram_heart[j,i] == 999) (Fram_heart[j,i]==".") else (Fram_heart[j,i]==Fram_heart[j,i]) #Question 3: Create a dataset cardio which only contains patinets who had a cardio risk factor cardio<-fram_heart[which(apply(fram_heart[,4:6],1,sum)>0),] nrow(cardio) ##1494 patients had at least 1 cardiovascular risk factor