Emm*_*man 6 bash shell command-line r rscript
我正在利用Rscript通过 bash 运行 R 脚本,并且我想指定要传递给脚本本身内的函数的参数。具体来说,我想传递指定的参数:
.csv) 和当列名包含波浪号 ( ~)时,我遇到了问题。我试过用反引号包裹列名,但仍然不成功。
我想编写一个脚本,该脚本以.csv格式接收数据文件,并根据用户的选择为一个变量绘制直方图。
plot_histogram <- function(path_to_input, x_var) {
data_raw <- read.csv(file = path_to_input)
path_to_output_folder <- dirname(path_to_input)
png(filename = paste0(path_to_output_folder, "/", "output_plot.png"))
hist(as.numeric(na.omit(data_raw[[x_var]])), main = "histogram", xlab = "my_var")
replicate(dev.off(), n = 20)
}
Run Code Online (Sandbox Code Playgroud)
set.seed(123)
df <- data.frame(age = sample(20:80, size = 100, replace = TRUE))
write.csv(df, "some_age_data.csv")
plot_histogram(path_to_input = "some_age_data.csv",
x_var = "age")
Run Code Online (Sandbox Code Playgroud)
正如预期的,我得到一个.png与图文件,保存到同一目录中的.csv是

plot_histogram.R
args <- commandArgs(trailingOnly = TRUE)
## same function as above
plot_histogram <- function(path_to_input, x_var) {
data_raw <- read.csv(file = path_to_input)
path_to_output_folder <- dirname(path_to_input)
png(filename = paste0(path_to_output_folder, "/", "output_plot.png"))
hist(as.numeric(na.omit(data_raw[[x_var]])), main = "histogram", xlab = "my_var")
replicate(dev.off(), n = 20)
}
plot_histogram(path_to_input = args[1], x_var = args[2])
Run Code Online (Sandbox Code Playgroud)
然后使用命令行运行 Rscript
$ Rscript --vanilla plot_histogram.R /../../../some_age_data.csv "age"
Run Code Online (Sandbox Code Playgroud)
也有效!
第 1 步:创建假数据
library(tibble)
set.seed(123)
df <- tibble(`age-blah~value` = sample(20:80, size = 100, replace = T))
write.csv(df, "some_age_data.csv")
Run Code Online (Sandbox Code Playgroud)
第 2 步:使用Rscript:
$ Rscript --vanilla plot_histogram.R /../../../some_age_data.csv "age-blah~value"
Run Code Online (Sandbox Code Playgroud)
hist.default(as.numeric(na.omit(data_raw[[x_var]])), main = "histogram", : 'breaks' 调用次数无效:plot_histogram -> hist -> hist.default 执行停止
使用时Rscript,如何传递指定包含波浪号的列名的参数?或者,如何.csv在Rscript?
谢谢!
您正在成功传递一个参数,该参数指定包含波浪号的列名。但是,read.csv已经“固定”了列名,因此它实际上不包含波浪号。
read.csv正在默默地将列名转换为age.blah.value. 使用check.names = FALSE使它age-blah~value。
data_raw <- read.csv(file = path_to_input, check.names = FALSE)
Run Code Online (Sandbox Code Playgroud)