R 如何将向量传递给函数的dots(…)参数
多个R函数具有和参数R 如何将向量传递给函数的dots(…)参数,r,R,多个R函数具有和参数…,允许您传递任意数量的参数。这方面的一个例子是粘贴函数,您可以向该函数提供任意数量的参数。但有时候,你不知道你想通过多少辩论 例如,假设我想在ggplot中生成一个绘图,其中我想通过两列的组合为点着色: df <- data.frame(x=rnorm(100), y=rnorm(100), cat1=sample(c(TRUE, FALSE), 100), ca
…
,允许您传递任意数量的参数。这方面的一个例子是粘贴
函数,您可以向该函数提供任意数量的参数。但有时候,你不知道你想通过多少辩论
例如,假设我想在ggplot中生成一个绘图,其中我想通过两列的组合为点着色:
df <- data.frame(x=rnorm(100),
y=rnorm(100),
cat1=sample(c(TRUE, FALSE), 100),
cat2=sample(c(TRUE, FALSE), 100),
cat3=sample(c(TRUE, FALSE), 100))
ggplot(df) + aes(x=x, y=y, col=paste(cat1,cat2) + geom_point()
使用syms
:
color_plot <- function(df, color_by) {
color_by <- syms(color_by)
ggplot(df) + aes(x=x, y=y, col=paste(!!!color_by)) + geom_point()
}
color\u plot另一种方法是使用quos
如果您更喜欢输入不带引号的列名而不是列表:
library(ggplot2)
library(rlang)
color_plot <- function(df, ...) {
color_by = quos(...)
ggplot(df) + aes(x=x, y=y, col=paste(!!!color_by)) + geom_point()
}
color_plot(df, cat1, cat2, cat3)
库(ggplot2)
图书馆(rlang)
彩色打印?do.call
,例如do.call(what=paste,args=…)
。虽然我仍然不认为这在ggplot
美学映射中能很好地工作-paste
返回一个字符串aes()
需要不带引号的列名。我认为你缺少了aes
的括号,这只有在整洁感知环境中使用时才有效。所以我不能只做x是的,这就是rlang的工作原理,你的问题包括了库(rlang),所以这是你的假设。一个基本的解决方案是:color\u是的,我试图解决的问题是一个ggplot问题,所以这就是我要寻找的,我有一个想法rlang将是一种方法,但一旦我遇到它,我就会想‘哇,这太棒了,我还能在哪里使用它’。
color_plot <- function(df, color_by) {
color_by <- syms(color_by)
ggplot(df) + aes(x=x, y=y, col=paste(!!!color_by)) + geom_point()
}
library(ggplot2)
library(rlang)
color_plot <- function(df, ...) {
color_by = quos(...)
ggplot(df) + aes(x=x, y=y, col=paste(!!!color_by)) + geom_point()
}
color_plot(df, cat1, cat2, cat3)