[英]Passing arguments to R script in command line (shell/bash): what to do when column names contain tilde (~)
我正在利用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)
}
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")
正如預期的那樣,我得到了一個帶有繪圖的.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])
然后使用Rscript
通過命令行運行
$ Rscript --vanilla plot_histogram.R /../../../some_age_data.csv "age"
也有效!
第 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")
第 2 步:使用Rscript
:
$ Rscript --vanilla plot_histogram.R /../../../some_age_data.csv "age-blah~value"
hist.default(as.numeric(na.omit(data_raw[[x_var]])), main = "histogram", : 'breaks' 調用次數無效:plot_histogram -> hist -> hist.default 執行停止
使用Rscript
,如何傳遞指定包含波浪號的列名的參數? 或者,如何在Rscript
的框架內處理列名中具有這種波浪號格式的.csv
文件?
謝謝!
您正在成功傳遞一個參數,該參數指定包含波浪號的列名。 但是, read.csv
已經“固定”了列名,因此它實際上並不包含波浪號。
read.csv
正在默默地將列名轉換為age.blah.value
。 使用check.names = FALSE
使其成為age-blah~value
。
data_raw <- read.csv(file = path_to_input, check.names = FALSE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.