user2533660 user2533660 - 4 months ago 21
R Question

R - How do I pass the value of a variable as an argument?

Noob here. I am trying to pass the value of "xmove1," "xmove2," and "xmove3" into the filter command.

xmove1 <- "X3"
xmove2 <- "X1"
xmove3 <- "X5"

xtemp <- filter(fullTable, xmove1 == 1, xmove2 == 2, xmove3 == 3)


The problem is that instead of reading the value of xmove1, it seems to be reading it as a string - "xmove1."

I have also tried to use "as.name," but the result seems to be the same.

xtemp <- filter(fullTable, as.name(xmove1) == 1, as.name(xmove2) == 2, as.name(xmove3) == 3)

Answer

If you want to dynamically supply column names, use the standard evaluation alternatives of the dplyr function (see vignette("nse") for more info).

You can

filter_(fullTable, .dots=list(
    bquote(.(as.name(xmove1)) == 1), 
    bquote(.(as.name(xmove2)) == 2), 
    bquote(.(as.name(xmove3)) == 3)))
Comments