我有一个从数据生成散点图的函数,其中提供了一个参数来选择用于为点着色的列。这是一个简化版本:
library(ggplot2)
plot_gene <- function (df, gene) {
ggplot(df, aes(x, y)) +
geom_point(aes_string(col = gene)) +
scale_color_gradient()
}
wheredf
是一个data.frame列x
,y
, ,然后是一堆基因名称。这适用于大多数基因名称;然而,有些有破折号,这些失败:
print(plot_gene(df, "Gapdh")) # great!
print(plot_gene(df, "H2-Aa")) # Error: object "H2" not found
看来gene
变量正在被解析("H2-Aa"
变成H2 - Aa
)。我怎样才能解决这个问题?有没有办法表明一个字符串不应该通过eval
in aes_string
?
可重现的输入
如果您需要一些输入来玩,这会像我的数据一样失败:
df <- data.frame(c(1,2), c(2,1), c(1,2), c(2,1))
colnames(df) <- c("x", "y", "Gapdh", "H2-Aa")
对于我的真实数据,我使用read.table(..., header=TRUE)
并获取带有破折号的列名,因为原始数据文件有它们。