2 years ago
#386800

IVIM
Using dplyr and data.table with get() for reusibility and shiny - good practices in R
Main question:
What's the best way to pass variables to dplyr and data.table - when variables are not hard-coded but are acquired from user at run-time, as when entered from Shiny?
Example 1:
df <- mtcars
dt <- mtcars %>% as.data.table
input <- list(); input$newcol="rate"; input$numerator="cyl"; input$denominator="wt"
df <- df %>% mutate(get(input$newcol)=get(input$numerator)/get(input$denominator))
dt[ , ':='(get(input$newcol)=get(input$numerator)/get(input$denominator))]
Example 2: (The same as example 1 but referencing columns by number)
input$numerator=2; input$denominator="6"
Example 3 (The same as examples 1 and 2, but using array of variables ):
input$newcols=paste("rate_", 1:3);
input$numerators=1:3
# or input$numerators=c("cyl", "disp", "hp");
input$denominators=5:7
And tangent questions:
Q1: What is wrong in the example 1 above? (the error message is shown below)
Error: unexpected '=' in "df %>% mutate(get(input$newcol)="
Q2: Can/Should one use as.name() instead of get() ? When one should use the former, and when the latter?
PS: I'm suprised this is not normally discussed anywhere in early stages of R learning books (including from Harley and Matt Doyle). If I would teach R, this would be the first skill I would teach - how to write code that it is reusable with any variable (not with just hard-coded variable), like we teach C++ or Java. Comment on this PS are also welcome.
r
dplyr
data.table
0 Answers
Your Answer