R 如何更改传递给“的列名?”;填写「;以编程方式?

R 如何更改传递给“的列名?”;填写「;以编程方式?,r,ggplot2,R,Ggplot2,我需要绘制一个面积堆栈图,在该图中,可以通过更改“stringholder”变量以编程方式更改填充。下面是我想做的一个例子 this_group_label <- "Roots & Tubers" #[...lots of code in which a data frame df_plot is created with a column named "Roots & Tubers...]" gg <- ggplot(df_plot, aes(x = year, y

我需要绘制一个面积堆栈图,在该图中,可以通过更改“stringholder”变量以编程方式更改填充。下面是我想做的一个例子

this_group_label <- "Roots & Tubers"
#[...lots of code in which a data frame df_plot is created with a column named "Roots & Tubers...]"
gg <- ggplot(df_plot, aes(x = year, y = `Pctge CC`, fill = this_group_label))
gg <- gg + geom_area(position = "stack")
gg
get()

此组标签此功能:

this_group_label <- "Roots & Tubers"
#[...lots of code in which a data frame df_plot is created with a column named "Roots & Tubers...]"
fill_label <- paste0("`", this_group_label, "`")
gg <- ggplot(df_plot, aes_string("year", "`Pctge CC`", fill = fill_label))
gg <- gg + geom_area(position = "stack")
gg

此组标签
rlang::sym
获取字符串并将其转换为符号。您只需使用
,因为
aes
需要未计算的表达式:

library(rlang)

gg <- ggplot( df_plot, aes(x=year, y=`Pctge CC`, fill = !!sym(this_group_label)) )
gg <- gg + geom_area(position = "stack")
gg
库(rlang)

gg不要在
aes_字符串
版本中使用反勾号,只需执行
y=“Pctge CC”
@Gregor执行了您的更正,仍然在FUN(X[[i]],…)中获得错误
错误:未找到对象“根”
请参阅本期@hadley的评论:。复制oid:。此外:请发布一个最小的可复制示例。如果
fill\u标签
值包含空格,则此操作将失败。要修复它,您需要绕道一点:
deparse(as.name(fill_label),backtick=TRUE)
(请注意,在字符串周围加上backtick的天真解决方案也可能失败)。@KonradRudolph
这个组标签有空格,但是这个组标签被公认为天真和业余的
paste0(
”)修复了,“
技巧。有了这个技巧,
fill\u label
将永远不会包含空格。对,我忽略了这一点。但正如前面提到的,我认为这可能会失败(但不适用于简单的空格)。我之前的评论中至少显示了一种更健壮、更具描述性的方法。
this_group_label <- "Roots & Tubers"
#[...lots of code in which a data frame df_plot is created with a column named "Roots & Tubers...]"
fill_label <- paste0("`", this_group_label, "`")
gg <- ggplot(df_plot, aes_string("year", "`Pctge CC`", fill = fill_label))
gg <- gg + geom_area(position = "stack")
gg
library(rlang)

gg <- ggplot( df_plot, aes(x=year, y=`Pctge CC`, fill = !!sym(this_group_label)) )
gg <- gg + geom_area(position = "stack")
gg