2017-05-15 14 views
2

사용자 정의 함수로 호출하면 geom_hline 또는 geom_vline 문제가 발생했습니다. 벡터. 내가 기능없이 그 기능 body.eg 내 facet_grid()를 추가 할 때까지 잘 작동하는 것 같다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") 

기능 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) 
}