Programmatically choosing which variables to put into dplyr pipe
I'm working with datasets (from smartphone experience sampling) where I have to very frequently performed grouped operations (such as find the variability of a measure within each person, or within each day within each person, etc). Typical code might look like the code below, which calculates within-day variability for some variables, then takes the mean of the within-day variability and joins it to the original data. output <- group_by(mydata, id, day) %>% mutate_at(vars(angr, sad, guil, anx, hap), funs(sd(., na.rm = TRUE))) %>% ungroup() %>% group_by(id) %>% summarize_at(vars(angr, sad, guil, anx, hap), funs('var_day_mean' = mean(., na.rm = TRUE))) %>% join(mydata, .) What I want to do is be able to save this as a function so that instead of having to type out angr, sad, guil, anx, hap many times over, I can call this code (and slight variations on it saved as different functions) on a vector of variable names in a string. So the desired functionality is: vars <- c('angr', 'sad', 'guil', 'anx', 'hap') output <- myfunc(vars) Where myfunc performs the piped operations above. I'm aware that there is a vignette for non standard evaluation using dplyr but it's very limited and doesn't cover mutate or most of what I need to do with this use case, so would appreciate any insight. Reproducible example - what I desire is essentially that the below code work, but currently the dplyr pipe cannot take vars as a character vector the way I have input it. data <- data.frame('ID' = rep(1:10, each = 10), 'day' = rep(c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2), 10), 'anx' = rnorm(100), 'sad' = rnorm(100), 'hap' = rnorm(100)) vars = c('anx', 'sad', 'hap') out <- group_by(data, ID, day) %>% mutate_at(vars, funs(sd(., na.rm = TRUE)))
With mutate_at you can simply supply the names of the columns as a vector: mtcars %>% mutate_at(c("mpg", "hp"), funs(mean)) This should do the trick.
plotting using “factoextra” package
time series contour plot with non-uniform intervals
How to create a bar plot with 2 columns containing sum of 0s and 1s?
How can i split a string based on word boundary in R? [duplicate]
Error in Knn, 'train' and 'class' have different lengths - R Code
How could a matrix hold different data types when coercing from a list?
Why is webshot not working with leaflets in R shiny?
How do I split a list containing data frames into the individual data frames?
No neighbours in sample using spatcounts package in R - Error: NA/NaN/Inf in foreign function call (arg 1)
R weird data frame subset formula vs. no formula
Split a whole column of a data frame and keep only the first part
Apply an element-wise function to data.table columns
Exclude data in R based on minimum sample size
How to make bar plot with dplyr in shiny dashboard
Elementwise vector multiplication between all rows of two data frames / matrices
R: network plot