7 ms·
That's a nice tutorial for beginners, though sticking dplyr code in functions is skirting dangerously close to the world of hurt that is non-standard evaluati
by _Wintermute 10y ago
That's a nice tutorial for beginners, though sticking dplyr code in functions is skirting dangerously close to the world of hurt that is non-standard evaluation.
The example:
join_and_summarize <- function(df, colour_df){
left_join(df, colour_df, by = "cyl") %>%
group_by(colour) %>%
summarize(mean_displacement = mean(disp))
}
Will go really badly wrong if someone following the tutorial simply replaces the `disp` with a function argument.
- dandermotj 10y agoThe standard evaluation versions of all dplyr functions are available, just add an underscore to the end: filter_, select_, ...
- minimaxir 10y agoA cool feature of select_ I discovered accidently is that you can pass in a vector of column names to get the corresponding columns, which is much easier than abusing which() to lookup indices.
- _Wintermute 10y agoNot sure if I'm misunderstanding, but you've always been able to slice on a vector of column names. cols <- c("colA", "colB") dataframe[, cols]
- minimaxir 10y agoTrue, although not as a part of a dplyr chain, which is cleaner.
- disgruntledphd2 10y agoextract and extract2 from magrittr also work. I do normally use dplyr though.
- _Wintermute 10y agoI'm of the opinion that non-standard evaluation probably isn't the best introduction for converting people from excel to R. As nice as dplyr's syntax is for beginners you can quickly get into the whole ugly side of R. Also it's often not as simple as just prefixing an underscore, you end up reading the lazyeval vignette and messing about with quote() and formula syntax.
- gordon_shotwell 10y agoThat's a good point, I'm not exactly sure what the best practice is for using NSE vs. SE functions within functions. My practice is to just use the NSE version unless I have a good reason not to. Generally my goal with teaching beginners to use R is to just not be afraid of functions as the barrier tends to be feeling like they can use them at all rather than using them in the safest way.
- hadley 10y agoYeah, NSE sucks in dplyr, but it'll be fixed soon :)