【发布时间】: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 <- c("test1", "test2", "test3"); paste("This is the", seq_along(Path), "text") -
@sindri_baldur 我已经用实际代码而不是虚拟示例编辑了问题。
标签: r list function for-loop lapply