R 如何在函数中填充向量?

R 如何在函数中填充向量?,r,R,下面代码的目的是用包含在单独向量tv中的系统命令结果填充向量textVector: tv = c("ls" , "ls -l") textVector = c() mf <- function(f) { cmdToRun <- f aa <- system(cmdToRun , intern=TRUE) textVector <- c(textVector, aa) } lapply(tv , mf) 使用只包含第一个命令的结果的textVector,在

下面代码的目的是用包含在单独向量
tv
中的系统命令结果填充向量
textVector

tv = c("ls" , "ls -l")
textVector = c()

mf <- function(f) {
  cmdToRun <- f
  aa <- system(cmdToRun , intern=TRUE)
  textVector <- c(textVector, aa)
}

lapply(tv , mf)

使用只包含第一个命令的结果的
textVector
,在本例中是“ls”,而不是“ls-l”的结果您必须将调用的
lappy
结果保存到一个新变量中。。。在您的例子中,它将生成一个包含两个字符向量的列表

result<-lapply(tv , mf)

result如果您想在函数中更改父环境中的对象,您需要使用
谢谢,似乎textVector只包含第一个命令的结果,在本例中是“ls”,而不是“ls-l”的结果,它对我有效。。。我在textVector中有ls和ls-l的结果。@blue sky我已经
rm(list=ls())
并在文件夹中运行了代码。结果附呈。我已经在Linux和Windows上测试了我的答案-它可以工作。我很想知道为什么它对你不起作用。如果您在*uni系统上,请检查.bashrc文件。您应该提到您正在“使用”我的答案。否则,我可能只是发布你的问题。
result<-lapply(tv , mf)
tv = c("ls" , "ls -l")
textVector = c()

mf <- function(f) {
  cmdToRun <- f
  aa <- system(cmdToRun , intern=TRUE)

  textVector <<- c(textVector, aa)

}

lapply(tv , mf)
textVector
#[1] "file1"
#[2] "file2"
#[3] "total 8"
#[4] "-rw-r--r-- 1 [deleted] 3 Nov  6 18:24 file1"
#[5] "-rw-r--r-- 1 [deleted] 5 Nov  6 18:24 file2"