运行 带有 openssl 的 Rscript 系统命令

Running Rscript System commands with openssl

我在让 R 为我执行系统命令时遇到了一些问题。系统命令是openssl,很基础

我在 Windows 系统上。

如果我在 cmd.exe 提示符或 powershell 上执行以下代码,它会按预期工作:

## echo "the name of the dog is bruce" | openssl enc -base64
dGhlIG5hbWUgb2YgdGhlIGRvZyBpcyBicnVjZQo=

但是,当我尝试在我的 R 脚本中将其转换回原始字符串时,它不起作用:

mydata <- "dGhlIG5hbWUgb2YgdGhlIGRvZyBpcyBicnVjZQo="
system(sprintf("echo '%s' | openssl enc -base64 -d", mydata))

它抱怨找不到 echo

Warning message:
'echo' not found

我知道我可以下载一些包,但是,我想使用 R 附带的基础包来解决这个问题。因为 openssl 似乎不是基础的一部分,所以我求助于以上方法(我知道效率不高所以请放轻松)。

我试过:

system2(sprintf("echo '%s' | openssl enc -base64 -d", mydata))

shell(sprintf("echo '%s' | openssl enc -base64 -d", mydata))

None 其中有效。

使用 shell(),提供 openssl 的完整文件路径,它应该可以工作。请注意,您需要使用参数 intern = TRUE 以便它 returns 一个可以分配的 R 对象。

mydata <- "dGhlIG5hbWUgb2YgdGhlIGRvZyBpcyBicnVjZQo="
shell(sprintf("echo %s | \"C:/Tools/openssl-1.1.1/openssl.exe\" enc -base64 -d", mydata), intern = TRUE)

[1] "the name of the dog is bruce"

为了完整性,使用 openssl 库:

library(openssl)

str_enc <- base64_encode("the name of the dog is bruce")
rawToChar(base64_decode(str_enc))

[1] "the name of the dog is bruce"