首页 > 解决方案 > 如何在 R 和 Shell 脚本中调用 Perl 变量?

问题描述

我有一个 Shell 脚本和一个 R 脚本都与 Perl 脚本链接。在 Perl 脚本中有用户定义路径,我也想将该路径用于 Shell 脚本和 R 脚本。需要进行哪些更改?这是 Perl 脚本:

print "Enter the path to your input file:";
chomp(my $user_path = <STDIN>);
my $path = $user_path // $default_path;  # $path  is path for Perl script
print "The path we'll use is: $path";
........................
........

这是 R 脚本:

x <- read.table($path."/text.txt", header=F) # how to introduce $path as path for R script
library(plyr)
df <- ddply(x, .(x$V1,x$V2, x$V3), nrow)
..............
.............

($path) 适用于 Perl 脚本,但不适用于 R。我想在 R 和 Shell 脚本中调用 Perl 变量 ($path)。如何在 R 和 Shell 脚本中使用 $path 作为路径?

标签: rshellperl

解决方案


只需在您的systemexecini perl 上使用 $path 作为参数。它会将 arg 发送到 shell 脚本,然后将其用作 arg 的Rscript.

例如,我有 3 个脚本。开始了。

root@analist:~/test# cat file.pl
#!/usr/bin/perl
#Input file
print "[Perl] Enter file:";
chomp(my $filepath = <STDIN>);
#Send to bash script
my @cmd = ('./file.sh');
push @cmd, $filepath;
system(@cmd);
root@analist:~/test# cat file.sh
#!/bin/bash
echo "[Bash] Filename: $1"
Rscript file.R $1
root@analist:~/test# cat file.R
args <- commandArgs(TRUE)
fileTxt <- args[1]
cat(paste('[R] File:', fileTxt, '\n'))
root@analist:~/test# ./file.pl
[Perl] Enter file:test.txt
[Bash] Filename: test.txt
[R] File: test.txt

我希望这个答案能有所帮助。


推荐阅读