################################################################################ # PS239 - FALL 2006 # HINTS FOR PROBLEM SET 2 ################################################################################ # This code will show you how to transform your data into a matrix # and give you some hints to use functions, adn to add an intercept to your regressions # 0) First, load your libraries library(MASS) library(foreign) # 1) Convert your data into a matrix # Read the data into an object (my object is called "data.ps1") data.ps1<-read.dta(file="W:/Teaching/Fall2006_PolSci239/ProblemSets/ProblemSet1/ME_households.dta") # Note that data.ps1 is now a data frame class(data.ps1) # But we need our data to be a matrix, so we will use the "data.matrix()" function # This function transforms a data frame into a matrix # First, select the variables that you want to include in the matrix and create a smaller data frame smaller.data.ps1<-data.frame(data.ps1$c411a,data.ps1$c414,data.ps1$c415) # Now that you have created the smaller data frame, go ahead and transform this data frame into a matrix matrix1<-data.matrix(smaller.data.ps1) dim(matrix1) # So "matrix1" is a 1895x3 matrix that contains the variables c411a,c414, and c415 # Now you are ready to use matrix1 to do matrix computations ################ HOW TO ADD AND INTERCEPT ################################################### # You'll need to add an intercept to your regressions # THis means that your X matrix must have a column of ones # To add a column of ones to our data frame do the following rep(1,nrow(X)) # This creates a vector of lenght equal to the number of rows of X, adn puts a 1 in all the entries # So try ones<-rep(1,nrow(matrix1)) # Now create a data frame with this additional variable smaller.data.ps1.intercept<-data.frame(ones,smaller.data.ps1) smaller.data.ps1.intercept dim(smaller.data.ps1.intercept) # Note that we have an extra column of ones # And now transfrom this into a matrix matrix1<-data.matrix(smaller.data.ps1.intercept) # Done!!!! ################ FUNCTION HINTS ################################################### # We've seen in section how to use a function to perform matrix algebra operations # Just remember that if you use a function with many arguments # such as "myfunction<-function(x,y,z,w)" # when you pass the arguments to the function, you either respect the order # or use the names of the arguments # So myfunction(1,2,3,4) or myfunction(x=1,y=2,z=3,w=4) are equivalent # If you use the names, as in the latter case, the order does not matter # so myfunction(x=1,y=2,z=3,w=4) is the same as myfunction(x=1,w=4,y=2,z=3) # But if you do not specify the names, then the order does matter # hence myfunction(1,2,3,4) is different from myfunction(1,4,2,3)