尝试使用命令行参数时,在R中找不到对象错误

尝试使用命令行参数时,在R中找不到对象错误,r,ggplot2,R,Ggplot2,我试图通过命令行将一个数字传递给一个非常简单的R脚本来进行绘图 我得到了这个plot.r文件: args<-commandArgs(TRUE) vmcn<-as.integer(args[1]) library(ggplot2) library(grid) file<-read.table("my file.txt",header=F) ggplot(file,aes(x=V1))+geom_histogram(binwidth=1,aes(y=..count../vm

我试图通过命令行将一个数字传递给一个非常简单的R脚本来进行绘图

我得到了这个plot.r文件:

args<-commandArgs(TRUE)

vmcn<-as.integer(args[1])

library(ggplot2)
library(grid)

file<-read.table("my file.txt",header=F)

ggplot(file,aes(x=V1))+geom_histogram(binwidth=1,aes(y=..count../vmcn*100))+theme_bw()

ggsave(filename="myfile.pdf",width=4,height=4)
我得到了一个错误:

Error in eval(expr, envir, enclos) : object 'vmcn' not found
Calls: print ... <Anonymous> -> as.data.frame -> lapply -> FUN -> eval
Execution halted
eval(expr、envir、enclose)中出现错误:找不到对象“vmcn” 呼叫:打印…->as.data.frame->lappy->FUN->eval 停止执行
有人能告诉我出了什么问题吗?

这实际上与您通过命令行运行R无关。您的脚本也不能交互工作。这与
ggplot2
aes
功能搜索对象的方式有关。令人惊讶的是,默认情况下,它不会在全局环境中进行搜索。下面是您如何修复它的:

# some reproducible data 
set.seed(1)
vmcn <- 100
file <- data.frame(V1 = rnorm(1000))
# and the fixed plotting command 
ggplot(file, aes(x=V1)) +
  geom_histogram(binwidth=1, aes(y=..count..*100/get("vmcn", envir=.GlobalEnv))) +
  theme_bw()
#一些可复制的数据
种子(1)

vmcn这实际上与通过命令行运行R无关。您的脚本也不能交互工作。这与
ggplot2
aes
功能搜索对象的方式有关。令人惊讶的是,默认情况下,它不会在全局环境中进行搜索。下面是您如何修复它的:

# some reproducible data 
set.seed(1)
vmcn <- 100
file <- data.frame(V1 = rnorm(1000))
# and the fixed plotting command 
ggplot(file, aes(x=V1)) +
  geom_histogram(binwidth=1, aes(y=..count..*100/get("vmcn", envir=.GlobalEnv))) +
  theme_bw()
#一些可复制的数据
种子(1)

成功了!谢谢你的回答,我又学到了一些关于R的知识。我也遇到了。这似乎只发生在你使用特殊的
.var..
变量的美学上。它起作用了!谢谢你的回答,我又学到了一些关于R的知识。我也遇到了。这似乎只有在使用特殊的
.var..
变量时才会发生。