2

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

1 Answer 1

1

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()
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Jilber. Apologies I pasted in the wrong code (forgetting col1). I have edited it out. The second solution works perfectly. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.