用列名和ggplot2创建一个函数

时间:2019-04-16 19:50:05

标签: r ggplot2

我想在使用ggplot的自定义函数中传递列名,以便重新创建图形。

错误状态:

Error: All columns in a tibble must be 1d or 2d objects: * Column `x` 

如何更新函数,以便定义所需的列?

谢谢。

#DATA AND GRAPH
data("USArrests")
USArrests$IsHigh <- ifelse(USArrests[1] >= 13, 1 ,0)
ggplot(USArrests, aes(x=Assault, fill=factor(IsHigh)))+geom_density(alpha=0.25)+
geom_vline(aes(xintercept=mean(Assault[IsHigh==0],na.rm=T)),color="red",linetype="dashed",lwd=1)+
geom_vline(aes(xintercept=mean(Assault[IsHigh==1],na.rm=T)),color="blue",linetype="dashed",lwd=1)+
scale_x_continuous()+
  theme_classic()


##ATTEMPT AT FUNCITON
Test <- function(DATA, col1, col2){

ggplot(DATA, aes(x=col1, fill=factor(col2)))+
geom_density(alpha=0.25)+
geom_vline(aes(xintercept=mean(col1[col2==0],na.rm=T)),color="red",linetype="dashed",lwd=1)+
geom_vline(aes(xintercept=mean(col1[col2==1],na.rm=T)),color="blue",linetype="dashed",lwd=1)+
scale_x_continuous()+
  theme_classic()
}

#ERROR
Test(USArrests, "Assault", "IsHigh")

1 个答案:

答案 0 :(得分:1)

首先,在您的参数中使用col1,在函数主体中调用col而不是col1,其次,您需要使用get()来返回命名对象(col1col2)的值。试试这个...

Test <- function(DATA, col1, col2){
        ggplot(DATA, aes(x=get(col1), fill=factor(get(col2))))+
        geom_density(alpha=0.25)+
        geom_vline(aes(xintercept=mean(get(col1)[get(col2)==0],na.rm=T)),color="red",linetype="dashed",lwd=1)+
        geom_vline(aes(xintercept=mean(get(col1)[get(col2)==1],na.rm=T)),color="blue",linetype="dashed",lwd=1)+
        scale_x_continuous()+
        xlab(label = "Fixed Acidity Level")+
        ggtitle("Distribution of Fixed Acidity Levels")+
        theme_classic()
    }

Test(USArrests, "Assault", "IsHigh")

如果您不想使用get,那么...

Test <- function(DATA, col1, col2){

  col1 <- DATA[,col1] 
  col2 <- DATA[,col2]

  ggplot(DATA, aes(x=col1, fill=factor(col2)))+
    geom_density(alpha=0.25)+
    geom_vline(aes(xintercept=mean(col1[col2==0],na.rm=T)),color="red",linetype="dashed",lwd=1)+
    geom_vline(aes(xintercept=mean(col1[col2==1],na.rm=T)),color="blue",linetype="dashed",lwd=1)+
    scale_x_continuous()+
    xlab(label = "Fixed Acidity Level")+
    ggtitle("Distribution of Fixed Acidity Levels")+
    theme_classic()
}