将列名称传递给函数

时间:2016-11-30 21:31:18

标签: r ggplot2 dplyr

如何将此ggplot()调用转换为函数?我无法弄清楚如何让R识别我想要传递给函数的列名。我曾经遇到过几个类似的问题,但我没有成功地适应想法。有关substitute()的信息,请参见here

# setup
  library(dplyr)
  library(ggplot2)
  set.seed(205)
  dat = data.frame(t=rep(1:2, each=10), 
                   pairs=rep(1:10,2), 
                   value=rnorm(20))

# working example
  ggplot(dat %>% group_by(pairs) %>%
           mutate(slope = (value[t==2] - value[t==1])/(2-1)),
         aes(t, value, group=pairs, colour=slope > 0)) +
    geom_point() +
    geom_line() +
    stat_summary(fun.y=mean,geom="line",lwd=2,aes(group=1))

# attempt at turning into a function
    plotFun <- function(df, groupBy, dv, time) {
    groupBy2 <- substitute(groupBy)
    dv2 <- substitute(dv)
    time2 <- substitute(time)
    ggplot(df %>% group_by(groupBy2) %>%
             mutate(slope = (dv2[time2==2] - dv2[time2==1])/(2-1)),
           aes(time2, dv2, group=groupBy2, colour=slope > 0)) +
      geom_point() +
      geom_line() +
      stat_summary(fun.y=mean,geom="line",lwd=2,aes(group=1))
  }

# error time
  plotFun(dat, pairs, value, t)

更新

我接受了@joran的建议来看看这个答案,这就是我想出的:

library(dplyr)
library(ggplot2)
library(lazyeval)

plotFun <- function(df, groupBy, dv, time) {
    ggplot(df %>% group_by_(groupBy) %>%
             mutate_(slope = interp(~(dv2[time2==2] - dv2[time2==1])/(2-1),
                                    dv2=as.name(dv), 
                                    time2=as.name(time))),
           aes(time, dv, group=groupBy, colour=slope > 0)) +
      geom_point() +
      geom_line() +
      stat_summary(fun.y=mean,geom="line",lwd=2,aes(group=1))
  }

plotFun(dat, "pairs", "value", "t")

代码运行但情节不正确:

  

geom_path:每组只包含一个观察。你需要吗?   调整群体审美?

1 个答案:

答案 0 :(得分:1)

以下是所有评论者提供的工作解决方案:

# setup
  library(dplyr)
  library(ggplot2)
  library(lazyeval)
  set.seed(205)
  dat = data.frame(t=rep(1:2, each=10), 
                   pairs=rep(1:10,2), 
                   value=rnorm(20))


# function
  plotFun <- function(df, groupBy, dv, time) {
      ggplot(df %>% group_by_(groupBy) %>%
             mutate_(slope = interp(~(dv2[time2==2] - dv2[time2==1])/(2-1),
                                      dv2=as.name(dv), 
                                      time2=as.name(time))),
             aes_string(time, dv, group = groupBy, 
                        colour = 'slope > 0')) +
        geom_point() +
        geom_line() +
        stat_summary(fun.y=mean,geom="line",lwd=2,aes(group=1))
  }

# plot
  plotFun(dat, "pairs", "value", "t")