gpt4 book ai didi

r - geom_hline 或 geom_vline 似乎不接受矢量作为引用线,如果在函数内部调用并使用 facet_grid()

转载 作者:行者123 更新时间:2023-12-04 09:16:45 25 4
gpt4 key购买 nike

如果我在自定义函数下调用 geom_hline 或 geom_vline 并且它从向量中获取值,我就会遇到问题。在我在该函数主体中添加 facet_grid() 之前,它似乎工作正常。例如无功能

c<- data.frame(A = c("carr","bike","truck","carr","truck","bike","bike","carr","truck","carr","truck","truck","carr","truck","truck"),
B = c(10,20,30,23,45,56,78,44,10,20,30,10,20,30,67),
D = c(1,2,3,1,2,3,2,3,2,3,2,2,3,2,1))
a = c(1:4)*4
ggplot(c, aes(A,B, color = D))+
geom_point()+
facet_grid( .~D)+
geom_hline(yintercept = a,linetype = "dotted",size =0.3)

`

我明白了:enter image description here

具有功能

    tk_fun <- function(dat,x1,y1,clr){   # I need to have this a declared and defined with in function.  
a = c(1:4)*4.5 p <- ggplot(dat, aes_string(colnames(dat)[1],colnames(dat)[2], color = colnames(dat)[3]))+
geom_point()+ facet_grid( .~dat[,3])+
geom_hline(yintercept = a,linetype = "dotted",size =0.3) return(p) } tk_fun(c,"A","B","D")

使用函数我得到这个错误:

Error in $<-.data.frame(*tmp*, "PANEL", value = c(1L, 2L, 3L, 1L, : replacement has 15 rows, data has 4 I hope someone can help me in figuring out, how to do it through function, without an error. Thanks

最佳答案

问题在于您对构面的定义。您需要使用正确的变量名称创建适当的公式调用,而不是直接使用数据。使用 pasteas.formula 可以提供帮助。

tk_fun <- function(dat,x1,y1,clr){   # I need to have this a declared and defined with in function.  
a = c(1:4)*4.5
p <- ggplot(dat, aes_string(colnames(dat)[1],colnames(dat)[2], color = colnames(dat)[3]))+
geom_point() +
facet_grid(as.formula(paste('. ~', names(dat)[3]))) +
geom_hline(yintercept = a, linetype = "dotted", size =0.3)
return(p)
}

关于r - geom_hline 或 geom_vline 似乎不接受矢量作为引用线,如果在函数内部调用并使用 facet_grid(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43978525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com