R/lm.function.R

Defines functions lm.function

#' Linear models across multiple variables
#'
#' Estimates p-values of geochemical data
#'
#' @param data data frame
#' @param cruise subsetting variable (numeric)
#' @param x independent variable of our linear model
#' @param y dependent variable of the linear model
#' @return a table of p-values
#'
#' @importFrom dplyr filter
#' @importFrom magrittr %>%
#' @export
lm.function <- function(data, cruise, x = "Depth_m", y) {
	# Subset the data to a particular cruise
	dat_subset <- data %>%
		filter(Cruise == cruise)

	# Create an empty list to hold results
	pval <- list()

	for (y.variable in y){
		# Fit a linear model
		model <- lm(dat_subset[[y.variable]] ~ dat_subset[[x]])

		# Summarize model and extract p-values
		sum <- summary(model)
		pval[[y.variable]] <- sum$coefficients[, "Pr(>|t|)"]
	}

	pval <- do.call(rbind, pval)
	pval <- as.data.frame(pval) # turn pval into a data frame

	# create dynamic column names
	col1 <- paste(colnames(pval)[1], ".p")
	col2 <- paste(x, ".p")
	colnames(pval) <- c(col1, col2)
	print(pval)
}
GilHenriques/intermediate_R documentation built on Dec. 31, 2020, 12:04 p.m.