Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Investigating the wrapr let function
##### set up#######
library(dplyr)
library(wrapr)
data<-structure(list(Location = c("AreaZ", "AreaZ", "AreaZ", "AreaZ",
"AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ",
"AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ",
"AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ",
"AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ",
"AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ",
"AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ",
"AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ",
"AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ", "AreaZ",
"AreaZ", "AreaZ", "AreaZ", "AreaZ"), Date = structure(c(14761,
14791, 14822, 14853, 14883, 14914, 14944, 14975, 15006, 15034,
15065, 15095, 15126, 15156, 15187, 15218, 15248, 15279, 15309,
15340, 15371, 15400, 15431, 15461, 15492, 15522, 15553, 15584,
15614, 15645, 15675, 15706, 15737, 15765, 15796, 15826, 15857,
15887, 15918, 15949, 15979, 16010, 16040, 16071, 16102, 16130,
16161, 16191, 16222, 16283, 16314, 16344, 16375, 16436, 16467,
16495, 16526, 16556, 16587, 16617, 16648, 16679, 16709, 16770
), class = "Date"), y = c(6, 3, 8, 18, 18, 2, 15, 11, 24, 11,
13, 13, 11, 10, 19, 5, 12, 14, 20, 3, 22, 15, 16, 24, 10, 18,
18, 38, 15, 23, 24, 23, 27, 27, 31, 18, 20, 20, 26, 22, 19, 21,
26, 25, 19, 19, 31, 23, 23, 21, 28, 23, 28, 35, 23, 29, 38, 22,
25, 23, 28, 33, 31, 20)), class = "data.frame", row.names = c(NA, -64L), .Names = c("Location", "Date", "y"))
####### end of setup#############
## define functions:
NSE_median_rows <- function(df, groupvar,x,nrows=NULL) {
#get the first rows for median calculations
MedianRows<- df %>%
dplyr::arrange_(.dots = lazyeval::lazy(x)) %>%
dplyr::group_by_(.dots = lazyeval::lazy(groupvar)) %>%
dplyr::slice_(~1:nrows)
return(MedianRows)
}
wrapr_median_rows <- function (dframe,datecol,groupvar=NULL,colname,nrows=9) {
mapping = list(COL=colname,DATES=datecol)
if(!is.null(groupvar)) {
wrapr::let(list(GROUPVAR= groupvar),
dframe %>%
dplyr::group_by(GROUPVAR)-> dframe
)
}
wrapr::let(mapping,
{
dframe %>%
dplyr::arrange(DATES)%>%
dplyr::filter(row_number(DATES) %in% c(1:nrows)) %>%
#dplyr::mutate(baseline = median(COL))%>%
dplyr::ungroup()
})
}
####compare use####
#interactive dplyr:
interactive_data <- data %>%
arrange(Date) %>%
group_by(Location) %>%
filter(row_number(Location) %in% c(1:9)) %>%
ungroup()
#NSE/lazyeval:
NSE_data <- NSE_median_rows(data,Location,Date,9)
##wrapr let :
wrapr_let_data <- wrapr_median_rows(data,'Date','Location','y',9)
#compare
interactive_data
NSE_data
wrapr_let_data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment