I'm trying to create a function to combine the output from the package rmcorr
with ggplot
. The documentation for rmcorr
includes an example on how to render the output with ggplot
. I'm having trouble getting the grouping variable working for my custom function (3rd code paragraph below).
Here is the code and the following graph, without grouping variable for facetting, and where everything looks fine:
rmcorr_fun_2 <- function(p,m1,m2) {
my.rmc <- rmcorr(participant = p, measure1 = m1, measure2 = m2, dataset = mtcars)
print(my.rmc)
p <- sym(p)
m1 <- sym(m1)
m2 <- sym(m2)
#grp <- sym(grp)
print(ggplot(data = mtcars, aes(x = !!m1, y = !!m2, group = factor(!!p), color = factor(!!p)))
geom_point(aes(colour = factor(!!p)))
geom_line(aes(y = my.rmc$model$fitted.values), linetype = 1))
#facet_wrap(.~(!!grp)))
}
Using same codes above but adding grp variable and removing the hashes for grouping:
rmcorr_fun_2 <- function(p,m1,m2,grp) {
my.rmc <- rmcorr(participant = p, measure1 = m1, measure2 = m2, dataset = mtcars)
print(my.rmc)
p <- sym(p)
m1 <- sym(m1)
m2 <- sym(m2)
grp <- sym(grp)
print(ggplot(data = mtcars, aes(x = !!m1, y = !!m2, group = factor(!!p), color = factor(!!p)))
geom_point(aes(colour = factor(!!p)))
geom_line(aes(y = my.rmc$model$fitted.values), linetype = 1)
facet_wrap(.~(!!grp)))
}
Gives the following error:
Error in sym(grp) : argument "grp" is missing, with no default
In addition: Warning message:
In rmcorr(participant = p, measure1 = m1, measure2 = m2, dataset = mtcars) :
'p' coerced into a factor
Called from: is_symbol(x)
CodePudding user response:
Instead of formula notation you have to wrap the faceting variable inside vars()
.
Also, instead of sym !!
you could simply make use of the .data
pronoun from rlang
in case you pass your column names as strings.
library(ggplot2)
library(rmcorr)
rmcorr_fun_2 <- function(p, m1, m2, grp) {
my.rmc <- rmcorr(participant = p, measure1 = m1, measure2 = m2, dataset = mtcars)
print(my.rmc)
ggplot(data = mtcars, aes(x = .data[[m1]], y = .data[[m2]], group = factor(.data[[p]]), color = factor(.data[[p]])))
geom_point(aes(colour = factor(.data[[p]])))
geom_line(aes(y = my.rmc$model$fitted.values), linetype = 1)
facet_wrap(vars(.data[[grp]]))
}
rmcorr_fun_2("cyl", "hp", "disp", "cyl")