r - How does dplyr pass in non-string parameters -
a lot of time in dplyr, like:
mydat %>% select(., mycol1, mycol2, mycol3) however, mycol1, mycol2, , mycol3 not strings text in r. how function know convert string.
for instance, if do:
dat <- data.frame(blue = rnorm(100), red= rnorm(100)) mysum <- function(dat, x, y){ browser() return (sum(dat$x)+ sum(dat$y)) } mysum(dat, blue, red)
your function going deliver 0 because $ infix function uses non-standard evaluation of right-hand side argument. (as point out, non-standard evaluation favorite mechanism in @hadley's functions. me it's barrier, many people seems welcome strategy.) if write function in manner (using $) fail want:
mysum(dat, blue, red) [1] 0 # wrong answer you said earlier that: "however, mycol1, mycol2, , mycol3 not strings text in r." guess trying mycol not enclosed in quotes , not character literal. in r such "text" (a sequence of unquoted characters) called 'symbol' or 'name'. (up point not talking dplyr.) if want write function deliver sum, (avoiding $ operation):
mysum <- function(dat, x, y){ return (sum(dat[[x]])+ sum(dat[[y]])) } mysum(dat, 'blue', 'red') [1] 19.16727 if want retrieve argument name matched parameter need use deparse( substitute(.))-maneuver:
dat <- data.frame(blue = rnorm(10), red= rnorm(10)) mysum2 <- function(dfrm, arg1, arg2){ a1 <- deparse(substitute(arg1)); a2 <- deparse(substitute(arg2)) sum(dfrm[[a1]]) +sum(dfrm[[a2]]) } mysum2(dat, blue, red) #[1] -0.5754979 mysum(dat, "blue", "red") #[1] -0.5754979 if want see how @hadley does, type:
> dplyr::select function (.data, ...) { select_(.data, .dots = lazyeval::lazy_dots(...)) } <environment: namespace:dplyr> .... doesn't deliver answer, it? need try this:
help(pac=lazyeval) ... has accompanying vignette named "lazyeval::lazyeval" --> "lazyeval: new approach nse". hadley argues lazyeval functions superior traditional substitute because carry forward environments, , suppose agree.
Comments
Post a Comment