【问题标题】:Add sequence in lapply R在 lapply R 中添加序列
【发布时间】:2019-08-30 14:38:26
【问题描述】:

我创建了一个使用lapply 运行的函数和一个名为Path 的列表:

CheckPath <- function(Path) {

  if (file.exists(Path)) {
    for (i in seq_along(Path)){
      cat(noquote(paste0('\nThe product is present. It can be found in the following path: \n\n', i, Path, '\n\n')))
      }
  } else {
    cat('\nThe product could not be found \n')
    stop()
  }
}

# Run the CheckPath function with Path as input
OutputPath <- lapply(Path, CheckPath)

Path 是一个包含某些文件的绝对路径的列表

所需的输出应该类似于 (if condition TRUE)

The product is present. It can be found in the following path 1 /my/path/
The product is present. It can be found in the following path 2 /my/path/
The product is present. It can be found in the following path 3 /my/path/

-- 编辑--

在函数中,如果我使用

cat(noquote(paste0('\nThe product is present. It can be found in the following path: ', seq_along(Path), Path, )))

给我这个输出:

The product is present. It can be found in the following path: 

1/mypath/to/file


The product is present. It can be found in the following path:

1/mypath/to/file


The product is present. It can be found in the following path: 

1/mypath/to/file

这非常接近我想要的,但我需要有一个带有1 2 3 等的序列。

【问题讨论】:

  • 为什么你使用lapply()test(Path) 将提供预期的输出?
  • 你为什么在这里使用lapply?您似乎根本没有使用传递给test 函数的变量var1。无论您传入什么,它都会返回相同的内容。我真的不确定您要在这里做什么。
  • Path &lt;- c("test1", "test2", "test3"); paste("This is the", seq_along(Path), "text")
  • @sindri_baldur 我已经用实际代码而不是虚拟示例编辑了问题。

标签: r list function for-loop lapply


【解决方案1】:

您可以尝试以下代码来获得您想要的结果。

path <-list("text1","text2","text3")
lapply(path,function(x){paste("This is the",which(path==x),x)})

【讨论】:

  • “哪个”的出色解决方案和巨大的贡献。希望你会发现这个平台很有用
猜你喜欢
  • 2015-07-04
  • 1970-01-01
  • 2015-04-23
  • 2019-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多