SOLUTION TO HOMEWORK 3. ### ----------- Part (a) > matcols = function(xvec, outcols) { outmat = cbind(rep(1,length(xvec)), xvec) if(outcols > 1) for(i in 2:outcols) outmat = cbind(outmat, xvec^i) outmat } > matcols(c(0,1,1,0,2.2,4,7),4) xvec [1,] 1 0.0 0.00 0.000 0.0000 [2,] 1 1.0 1.00 1.000 1.0000 [3,] 1 1.0 1.00 1.000 1.0000 [4,] 1 0.0 0.00 0.000 0.0000 [5,] 1 2.2 4.84 10.648 23.4256 [6,] 1 4.0 16.00 64.000 256.0000 [7,] 1 7.0 49.00 343.000 2401.0000 > matcols(2:5,1) xvec [1,] 1 2 [2,] 1 3 [3,] 1 4 [4,] 1 5 ## Here is another function that does the same thing: > matcol2 = function(xvec, outcols) outer(xvec, 0:outcols, function(x,y) ifelse(y==0, 1, x^y)) ### ------------ Part (b) > convtype = function(infram, charac=NULL, numer=NULL, bool=NULL){ tmpfram = infram charcols = unlist(lapply(tmpfram, is.character)) numcols = unlist(lapply(tmpfram, is.numeric)) boolcols = unlist(lapply(tmpfram, is.logical)) if(!is.null(charac) && charac == "factor" && sum(charcols)) for(i in (1:ncol(tmpfram))[charcols]) tmpfram[,i] = factor(tmpfram[,i]) if(!is.null(numer) && numer == "charac" && sum(numcols)) for(i in (1:ncol(tmpfram))[numcols]) tmpfram[,i] = as.character(tmpfram[,i]) if(!is.null(bool) && (bool=="charac" | bool=="numer") && sum(boolcols)) if(bool=="charac") for(i in (1:ncol(tmpfram))[boolcols]) tmpfram[,i] = as.character(tmpfram[,i]) else for(i in (1:ncol(tmpfram))[boolcols]) tmpfram[,i] = as.numeric(tmpfram[,i]) tmpfram } > auxfram = cbind.data.frame(numfac = as.character(11:20), numlab = rep(c(3,5),5), TF = rep(c(3,5),5) < 4, Lett = rep("",10)) > unlist(lapply(auxfram,class)) numfac numlab TF Lett "factor" "numeric" "logical" "factor" > auxfram$Lett = as.character(1:10) unlist(lapply(auxfram,class)) numfac numlab TF Lett "factor" "numeric" "logical" "character" > auxfram numfac numlab TF Lett 1 11 3 TRUE 1 2 12 5 FALSE 2 3 13 3 TRUE 3 4 14 5 FALSE 4 5 15 3 TRUE 5 6 16 5 FALSE 6 7 17 3 TRUE 7 8 18 5 FALSE 8 9 19 3 TRUE 9 10 20 5 FALSE 10 > unlist(lapply(convtype(auxfram, numer="charac"),class)) numfac numlab TF Lett "factor" "character" "logical" "character" > unlist(lapply(convtype(auxfram, bool="numer", numer="charac"),class)) numfac numlab TF Lett "factor" "character" "numeric" "character" ### Note that in this last case, it would be INCORRECT for the TF ## numeric column to have been converted to "character"