[英]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.我想在使用 ggplot 的自定义函数中传递列名,以便我可以重新创建图形。
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
).首先,在你的参数中有
col1
并且在函数体中你调用col
而不是col1
,其次你需要使用get()
来返回命名对象( col1
和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...如果你不想使用
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.