This problem is similar to a previous Stack question, except that the function calls the plyr/dplyr
package functions:
Using the example for illustration:
library(dplyr)
df <- data.frame(A=1:10, B=2:11, C=3:12)
func <- function(name,dat=df){
output <- dat %>%
select(A,name) %>%
arrange(desc(name))
}
The following call naturally produces an error:
result <- func(B)
While passing the arg. as character:
result <- func("B")
gives:
Error: All select() inputs must resolve to integer column positions.
Update:
Note that func
also calls the arrange()
function from dplyr
. For now, select_
solved 1/2 of the problem as suggested in the comment.
Using arrange_(desc(name))
throws this error: Error in eval(expr, envir, enclos) : incorrect size (1), expecting : 10
Update/Edit: As suggested in the comments, a resolution could be:
func <- function(name,dat=df){
output <- dat %>%
select_(~A,name) %>%
arrange_(interp(~desc(var), var=as.name(name)))
}
result <- func(B)
Is it possible to "patch" the following call to ggplot()
to func
? This is highly-desirable to automate the process:
plot <- ggplot(result, aes(x=A, y=B))+
geom_bar(stat='identity)