You can do this by using quosures. I think that the reprex ( https://www.jessemaegan.com/post/so-you-ve-been-asked-to-make-a-reprex ) below has the function you want.
suppressPackageStartupMessages(library(tidyverse))
df <- data.frame(month=rep(1:3,2),
student=rep(c("Amy", "Bob"), each=3),
A=c(9, 7, 6, 8, 6, 9),
B=c(6, 7, 8, 5, 6, 7))
t1 <- df %>%
gather(variable, value, -(month:student)) %>%
unite(temp, student, variable) %>%
spread(temp, value)
myspread <- function(df, key, value) {
# quote key
keyq <- rlang::enquo(key)
# break value vector into quotes
valueq <- rlang::enquo(value)
s <- rlang::quos(!!valueq)
df %>% gather(variable, value, !!!s) %>%
unite(temp, !!keyq, variable) %>%
spread(temp, value)
}
t2 <- df %>% myspread(student, c(A, B))
identical(t1, t2)
#> [1] TRUE
t2
#> month Amy_A Amy_B Bob_A Bob_B
#> 1 1 9 6 8 5
#> 2 2 7 7 6 6
#> 3 3 6 8 9 7
Created on 2018-02-20 by the reprex package (v0.2.0).