2015-09-03 43 views
1

我想使基于关闭此重复的例子的可重复使用的图函数内变换函数:传引用变量ggplot

test=data.frame(name=c('a', 'b', 'c', 'd', 'e', 'f'), amount=c(1,7,3,11,2,1)) 

ggplot(transform(test, name=reorder(name, -amount)), 
    aes(x=name, y=amount)) + 
    geom_bar(stat='identity') 

说我有越来越的transform功能正常工作的问题。

此功能,但不具备transform

p = function(df, x, y) { 
    ggplot(df, 
    aes_string(x=x, y=y)) + 
    geom_bar(stat='identity') 
} 

p(test, 'name', 'amount') 

当我添加了transform功能,我会得到相同的图表:

p_order = function(df, x, y) { 
    ggplot(transform(df, x=reorder(x, -y)), 
    aes_string(x=x, y=y)) + 
    geom_bar(stat='identity') 
} 

p_order(test, 'name', 'amount') 

但给出了一个警告:Warning message: In mean.default(X[[1L]], ...) : argument is not numeric or logical: returning NA

我试过在get,eval,中包装x=reorder(x, -y)的不同部位,quote。我一直在尝试几个小时,并认为这是某种promise概念,我只是没有抓住。

+2

所以看起来像'p =功能(DF,X,Y)变换(DF,名字=重新排序(X,Y))'这就是问题所在,甚至在它碰到ggplot之前 – user20650

回答

2

这将是最简单的使用分配和[[]]做,而不是变换:

p_order = function(df, x, y) { 
    df[[x]] <- reorder(df[[x]], -df[[y]]) 
    ggplot(df, aes_string(x=x, y=y)) + 
     geom_bar(stat='identity') 
} 
p_order(test, 'name', 'amount') 

如果你想使用变换,你可以用get使用它,但只有当它分配给新的列(否则你必须先从搞乱do.call

p_order = function(df, x, y) { 
    ggplot(transform(df, new_col = reorder(get(x), -get(y))), 
     aes_string(x = "new_col", y=y)) + 
     geom_bar(stat='identity') + 
     xlab(x) # to keep it looking the same 
} 
p_order(test, 'name', 'amount')