3

如果我在自定义函数下调用它并且它从向量中获取值,我一直面临 geom_hline 或 geom_vline 的问题。在我在该函数 body.eg 中添加 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)

`

我明白了:在此处输入图像描述

有功能

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

使用功能我收到此错误:

$<-.data.frame( , " PANEL *tmp*", value = c(1L, 2L, 3L, 1L, : 替换有 15 行,数据有 4 我希望有人能帮我弄清楚,如何通过函数做到这一点,没有错误。谢谢

4

1 回答 1

3

问题在于您对方面的定义。您需要使用正确的变量名称创建适当的公式调用,而不是直接使用数据。使用paste并且as.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) 
}
于 2017-05-15T11:47:12.180 回答