简体   繁体   中英

Creating a function with column names and ggplot2

I want to pass column names in a custom function that uses ggplot so I can recreate the graph.

The error states:

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

How can I update my function so I can define columns I want?

Thanks.

#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")

First of all, in your arguments you have col1 and in the function body you call col instead of col1 , secondly you need to use get() for returning the value of a named object ( col1 and col2 ). Try this...

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")

If you don't want to use get then...

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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM