簡體   English   中英

使用列名和 ggplot2 創建函數

[英]Creating a function with column names and 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")

首先,在你的參數中有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()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM