2015-08-14 185 views
0

我有一个数据帧dat,我试图用for循环绘图。我之所以在一个函数中使用forloop来绘制ggplots,是因为我想在后面多次调用这个函数。R ggplot for循环变数

> head(dat) 
     tpl  motif strand base score ipdRatio 
1: 24501 AAGTACTCG  0 A 51 3.108 
2: 58809 GAGTACTAC  0 A 69 4.095 
3: 65614 TAGTACTCA  0 A 61 3.341 
4: 78494 GAGTACTAC  0 A 92 4.968 
5: 92127 AAGTACTTA  0 A 23 1.702 
6: 193102 GAGTACTCG  0 A 96 5.255 

我不断收到一个错误:

Error in eval(as.symbol(x_val)) : error in evaluating the argument 'expr' in selecting a method for function 'eval': Error in as.symbol(x_val) : object 'x_val' not found

当我尝试调用像这样的功能:

plotme <- function(dataf,x_val,bin_width){ 
    print(ggplot(dataf, aes(x = eval(as.symbol(x_val)))) + 
      geom_histogram(binwidth = bin_width)) 
} 

ratioplot <- plotme(dat,"ipdRatio",.5) 

什么可能会在这里造成错误有什么建议?

+1

任何你把里面的'AES()'应在data.frame存在你喂'ggplot()'用。 –

+0

,但'dat'数据框中存在'ipdRatio'列。 – ALKI

+0

但不是'x_val',如错误消息中所述。 –

回答

1

我能够找到解决方案,我只需使用aes_string而不是aes来调用变量aes列值。

像这样:

plotme <- function(dataf,x_val,bin_width){ 
    print(ggplot(dataf, aes_string(x = x_val)) + 
      geom_histogram(binwidth = bin_width)) 
} 

ratioplot <- plotme(dat,"ipdRatio",15) 
+0

你可以继续,并检查这表明问题已被回答。 – aosmith

0

首先,我更喜欢aes()超过aes_string然后就去做

if (is.character(x_val)) {x_val <- which(names(dataf) == x_val)} 

这种方式指的列时,你可以把它作为数字或字符。

其次,你所做的功能有问题。

尝试和清除workspeace完全,并运行此此:

dat <- data.frame(ipdRatio=rnorm(100));library(ggplot2) 

plotme <- function(dataf,x_val,bin_width){ 
     localEnv <- environment() 
     if (is.character(x_val)) {x_val <- which(names(dataf) == x_val)} 
     print(ggplot(dataf, aes(x = dataf[,x_val])) + 
         geom_histogram(binwidth = bin_width)) 
} 

ratioplot <- plotme(dataf=dat,"ipdRatio",.5) 

将返回

Error in eval(expr, envir, enclos) : object 'dataf' not found 

函数调用DATAF = DAT根本就不是被制造,以及它的工作原理的原因你现在是因为你在全球环境中有dataf。

改变功能来指定环境作为本地

dat <- data.frame(ipdRatio=rnorm(100)); 

plotme <- function(dataf,x_val,bin_width){ 
     localEnv <- environment() 
     if (is.character(x_val)) {x_val <- which(names(dataf) == x_val)} 
     print(ggplot(dataf, aes(x = dataf[,x_val]),environment=localEnv) + 
         geom_histogram(binwidth = bin_width)) 
} 

ratioplot <- plotme(dataf=dat,"ipdRatio",.5) 
+0

您的原始函数和@ Chani的答案中的函数对我来说运行良好,无需添加'environment'参数。我绝对没有任何名为'datadf'的东西在我的环境中漂浮...... – aosmith

+0

'dataf' - 好吧也许这只是我的具体错误,但是具有干净的全局环境,并且没有在函数中指定env我得到错误。 – user2673238