# This function produces an intraspecific F-matrix for x phenotypic traits and y performance traits # using multiple regression. # It also runs a number of calculations to help interpret the F-matrix. fmat <- function(pheno,perf) { # pheno should be a data frame containing only phenotypic vars in columns, where rows are individuals. # perf should be a data frame with performance traits in columns, rows are individuals. # Individuals must be in the same order in pheno and perf. # Calculate how many phenotypic and performance traits there are. npheno <- length(pheno) nperf <- length(perf) perf_pheno <- cbind(perf,pheno) # Scale all of the perf and pheno variables to mean zero and SD 1 so that regression gives standardized coeffs. perf_pheno <- as.data.frame(scale(perf_pheno)) attach(perf_pheno) # Do a multiple regression on each perf variable using all pheno variables, place coefficients # and r-squares into objects. mreg_coefs <- NULL mreg_rsq <- rep(NA,nperf) for (i in 1:nperf) { frm <- as.formula(paste(names(perf)[i],paste(" ~ ",paste(names(pheno),collapse= "+")))) mreg_coefs[[i]] <- summary(lm(frm))$coefficients mreg_rsq[i] <- summary(lm(frm))$r.squared } names(mreg_coefs) <- names(perf) names(mreg_rsq) <- names(perf) detach() # Combine multiple regression slopes into an F-matrix, omitting the intercepts and label variables. F <- NULL for (i in 1:nperf) { F <- cbind(F,mreg_coefs[[i]][2:(npheno+1),1]) } colnames(F) <- names(perf) # Calculate row and col sums, row var, col var of abs values, FTF and FFT matrices Fabs <- abs(F) rsum <- apply(F,1,sum) csum <- apply(Fabs,2,sum) rvar <- apply(F,1,var) cvar <- apply(Fabs,2,var) FTF <- (t(F)) %*% F FFT <- F %*% (t(F)) rstats <- rbind(rsum,rvar) cstats <- rbind(csum,cvar) rgsum <- sum(abs(rsum)) cgsum <- sum(abs(csum)) gsum <- c(rgsum,cgsum) names(gsum) <- c("row","col") # Combine all the results into a list results <- list(mreg_coefs,mreg_rsq,F,FTF,FFT,rstats,cstats,gsum) names(results)<-c("mregs","rsq","F","FTF","FFT","row.stats","col.stats","grand.sum") results }