Skip to content

Instantly share code, notes, and snippets.

@WillForan
Last active March 19, 2020 11:44
Show Gist options
  • Save WillForan/c56e85bb3a35d1445fd21858833ff56a to your computer and use it in GitHub Desktop.
Save WillForan/c56e85bb3a35d1445fd21858833ff56a to your computer and use it in GitHub Desktop.
# dumpy data
MRSfake <-
data.frame(age=c(10,20,30),
roi=c('a','b','c'),
m1=c(1,2,3),
m2=c(4,5,NA))
# initial
MRS_age_effect <- function(region, metabolite) {
temp <- filter(MRS, roi == region)
temp <- filter(temp, !is.na(metabolite))
model <- lm(data=temp, metabolite ~ age)
summary(model)
}
# for testing outside the function
metabolite='m1'
region='a'
MRSfake %>% filter(roi == !!region)
# !! means use the value inside region instead of 'region' itself
# model formula x ~ y is R short hand for column names
# if instead we have variables of column names we need to contort a bit
fml <- formula(sprintf("%s ~ age", metabolite))
lm(fml, MRSfake)
# first pass
# 1. add MRS as input arugment
# 2. add nonstand evaluation (!! in dplyr command)
# 3. construction formula
MRS_age_effect <- function(MRS, region, metabolite) {
temp <- filter(MRS, roi == !!region)
temp <- filter(temp, !is.na(!!metabolite))
f <- formula(sprintf("%s ~ age", metabolite))
model <- lm(data=temp, f)
summary(model)
}
# check
MRS_age_effect(MRSfake,'b','m1')
# cleanup
# 1. put both filters expressions in same command
# 2. use pipe to avoid temp (for style, not performance)
# 3. use short variables to irritate BTC
MRS_age_effect <- function(d, r, m) {
f <- formula(sprintf("%s ~ age", m))
d %>%
filter(roi == !!r, !is.na(!!m)) %>%
lm(formula=f) %>%
summary
}
# check
MRS_age_effect(MRSfake,'b','m1')
### ignore me -- just for comparison
# with base R -- no tidyverse !! eval
# use M[logic,] M[,column] instead of filter
MRS_age_effect <- function(d, r, mt) {
f <- formula(sprintf("%s ~ age", mt))
tmp <- d[d$roi == r & !is.na(d[,mt]), ]
m <- lm(f, tmp)
summary(m)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment