使用索引而非列名指定列。

16

我编写了一个使用 ggplot 函数获取比例堆叠条形图的函数。目前我在此 ID 中使用列名。

PropBarPlot<-function(df, mytitle=""){
    melteddf<-melt(df, id="ID", na.rm=T)
    ggplot(melteddf, aes(ID, value, fill=variable)) + 
      geom_bar(position="fill") + 
      theme(axis.text.x = element_text(angle=90, vjust=1)) + 
      labs(title=mytitle)
}

我希望让它更通用。因此,我想使用列索引而不是列名。我尝试了以下代码:

PropBarPlot<-function(df, mytitle=""){
    melteddf<-melt(df, id=names(df)[1], na.rm=T)
    ggplot(melteddf, aes(names(df)[1], value, fill=variable)) + 
      geom_bar(position="fill") + 
      theme(axis.text.x = element_text(angle=90, vjust=1)) + 
      labs(title=mytitle)
}

但是没有用。有人能建议我如何做吗?谢谢。

1
可能是一个重复项,但尝试使用 aes_string(names(df)[1]) - baptiste
@baptiste 错误:无法将类“'uneval'”强制转换为数据框。 - Rachit Agrawal
没有包含数据的可重现示例,很难确定问题。 - baptiste
2个回答

14
正如@baptiste所指出的,你应该使用aes_string()而不是aes()来使用字符串表示x和y的值。此外,你应该在valuevariable中加上引号。
PropBarPlot<-function(df, mytitle=""){
  melteddf<-melt(df, id=names(df)[1], na.rm=T)
  ggplot(melteddf, aes_string(x=names(df)[1],y= "value", fill="variable")) + 
    geom_bar(position="fill") + 
    theme(axis.text.x = element_text(angle=90, vjust=1)) + 
    labs(title=mytitle)
}

1
aes_string()方法现已被软弃用。我在这里发布了另一种解决方案:https://dev59.com/d2Up5IYBdhLWcg3wXGu8#69286410 ,我认为它符合当前准引用实践。 - Bryan Shalloway

2

正如@Bryan Shalloway所指出的那样,aes_string()方法现在已经软弃用,并被整洁评估所取代。使用整洁评估方法,我的解决方案将是:

library(reshape)
library(ggplot2)

# let's start by creating an example dataframe
id <- c(1, 2, 3, 4)
var1 <- c(10, 20, 10, 20)
var2 <- c(6, 3, 2, 5)
df <- data.frame(id, var1, var2)

# Now let's build the function
PropBarPlot<-function(df, mytitle=""){
  # here I create a variable that contains the first element of the vector 
  # of df column names (it's a string)
  my_name <- colnames(df)[1]
  # here we melt, using the new variable as the id parameter
  melteddf<-melt(df, id=my_name, na.rm=T)
  # and here we plot, using the .data pronoun and the new variable
  ggplot(melteddf, aes(x = .data[[my_name]],y = value, fill = variable)) + 
    geom_bar(position="fill", stat="identity") + 
    theme(axis.text.x = element_text(angle=90, vjust=1)) + 
    labs(title=mytitle)
}

如果你想了解更多关于整洁评估的知识(包括逐步解释和实际示例),我衷心推荐Ian Lyttle的learnr教程,可以在https://ijlyttle.shinyapps.io/tidyeval/找到。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接