Created
May 20, 2015 20:14
-
-
Save Rekyt/3fd500d067cd34bce832 to your computer and use it in GitHub Desktop.
Automatically generates formula based on df column names
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example of automatic formula | |
# How to generate and test automatically different formulas | |
set.seed(1) # Makes it reproducible | |
library(dplyr) | |
library(lmerTest) | |
# Test data | |
df = data.frame(a = runif(30, 1, 10), b_sp = rnorm(30, 5, 20), | |
b_abs = runif(30, 0, 1), c_sp = rnorm(30, -3, 10), | |
c_abs = runif(30, 0, 1), | |
species = rep(c("specA", "specB"), each = 2, length.out = 30)) | |
# base formula | |
base.formula = "a ~ (1|species) +" | |
# Different models | |
sp.formula = df %>% | |
names() %>% # Get colnames of df | |
grep("_sp", ., value = T)%>% # Select names of interest | |
paste(collapse = " + ") %>% # joins all elements with '+' with spaces | |
paste(base.formula, .) %>% | |
as.formula() # Converts character string to formula | |
b.formula = df %>% | |
names() %>% # Get colnames of df | |
grep("b_", ., value = T)%>% # Select names of interest | |
paste(collapse = " + ") %>% # joins all elements with '+' with spaces | |
paste(base.formula, .) %>% | |
as.formula() | |
# Fit models | |
mod.sp = lmer(sp.formula, data = df) | |
mod.b = lmer(b.formula, data = df) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment