Last active
June 24, 2019 19:54
-
-
Save jirilukavsky/d10646b5a305681b49dd87b93b2c1674 to your computer and use it in GitHub Desktop.
Useful R code snippets that I often look for
This file contains hidden or 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
# --------- RStudio ------------------- | |
# knit from CLI | |
rmarkdown::render("test.Rmd", "html_document") | |
# --------- data manipulation --------- | |
# wide-to-long = gather, long-to-wide = spread | |
wide %>% | |
gather(key = column_name_of_column_names, | |
value = column_name_of_column_data, | |
-allvariables, -whichwewant, -ineachrow) | |
long %>% | |
spread(key = column_name_of_column_names, | |
value = column_name_of_column_data) | |
# --------- files and folders --------- | |
## find all files in folder | |
files <- dir("folder", pattern = "*.xlsx") | |
## load xlsx files based on the list | |
d <- | |
files %>% | |
file.path("folder", .) %>% | |
map(read_excel) %>% | |
bind_rows(.id = "id") | |
## using nest for collapsed data | |
d <- | |
participants %>% | |
group_by(id) %>% | |
do(nest(read_excel(.$filename))) | |
# --------- nested frames and models (purrr, broom) --------- | |
## nest (collapse and expand back) | |
dg <- d %>% group_by(id) %>% nest() | |
dg %>% unnest() | |
## calculate (no need for group_by) | |
models <- dg %>% | |
mutate(model1 = purrr::map(data, ~ lm(rt ~ distance, data = .))) %>% | |
mutate(model2 = purrr::map(data, ~ lm(rt ~ size, data = .))) %>% | |
gather(key = question, value = model, -data, -id) | |
## see results | |
models %>% unnest(model %>% purrr::map(broom::tidy)) | |
models %>% unnest(model %>% purrr::map(broom::glance)) | |
## without nesting, also: http://varianceexplained.org/r/broom-intro/ | |
### general summary | |
d %>% | |
group_by(id) %>% | |
do(broom::glance(lm(rt ~ x, data = .))) | |
### individual predictors/coefs | |
d %>% | |
group_by(id) %>% | |
do(broom::tidy(lm(rt ~ x, data = .))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment