2017-05-15 3 views
2

私はカスタム関数で呼び出すとgeom_hlineまたはgeom_vlineの問題に直面していました。ベクター。私は 機能がなければ、その関数のbody.eg内facet_gridを()を追加するまで、正常に動作するようですgeom_hlineまたはgeom_vlineは、ファンクション内で呼び出され、ファセットのグリッド()が使用されている場合、参照線のベクトルを受け入れていないようです

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

機能I aこのエラーが発生する:

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

+0

オブジェクトに名前「c」を割り当てないでください。 'c'はあなた自身のコードで使う基本的な基本関数です。 – Matt74

答えて

2

問題はファセットの定義にあります。正しい変数名で適切な数式呼び出しを作成し、データを直接使用する必要はありません。 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) 
} 
関連する問題