# body fat interaction effect example w <- c(89,88,66,59,93,73,82,77,100,67,57,68,69,59,62,59,56,66,72) f <- c(28,27,24,23,29,25,29,25,30,23,29,32,35,31,29,26,28,33,33) m <- c(rep(0,10),rep(1,9)) dat <- data.frame( weight=w , fat=f , male=m ) # model that ignores sex m <- lm( weight ~ fat , data = dat ) plot( dat$weight ~ dat$fat , cex=2 , pch=ifelse(dat$male==1,16,1) ) abline(m,col="red") # model that includes sex as main effect m2 <- lm( weight ~ fat + male , data = dat ) plot( dat$weight ~ dat$fat , cex=2 , pch=ifelse(dat$male==1,16,1) ) abline( a=coefficients(m2)[1] , b=coefficients(m2)[2] ,col="red") # female line abline( a=coefficients(m2)[1] + coefficients(m2)[3] , b=coefficients(m2)[2] ,col="red") # model that includes interaction m3 <- lm( weight ~ fat*male , data = dat ) plot( dat$weight ~ dat$fat , cex=2 , pch=ifelse(dat$male==1,16,1) ) abline( a=coefficients(m3)[1] , b=coefficients(m3)[2] ,col="red") # female line abline( a=coefficients(m3)[1] + coefficients(m3)[3] , b=coefficients(m3)[2] + coefficients(m3)[4] ,col="red") # male line # age at death example transformation age <- rexp( 600 , rate=0.1 ) hist(age , xlab="age at death") lines( c(mean(age),mean(age)) , c(0,250) , col="red" ) hist( log(age) , xlab="log(age at death)") lines( c(mean(log(age)),mean(log(age))) , c(0,250) , col="red" ) male <- c( rep(0,300) , rep(1,300) ) age <- c( rexp(300,rate=0.08) , rexp(300,rate=0.11) ) boxplot(age~male,xlab="male",ylab="age at death") boxplot(log(age)~male,xlab="male",ylab="log(age at death)") # fit model m <- lm( log(age) ~ male ) summary(m) # convert coef back to probability scale exp( coef(m)['male'] ) # works for confidence intervals too exp( confint(m)['male',] )