我想编写一个小函数,允许我根据语法糖$outnm = ".\" + $svr + "\" + $instnm + "_Jobs.csv"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "exec msdb.dbo.sp_help_job"
$SqlCmd.Connection = $cn
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0] | Select originating_server, name, description, owner, last_run_date, enabled | where {$_.Name -notlike 'sys*'} | export-csv -path $outnm -noType
和/或[[
灵活地为列表或环境组成递归提取表达式:
$
如何使用x <- list(a = list(b = 1))
> x[["a"]][["b"]]
[1] 1
代替substitute
和parse
的组合(因为这真的很慢)来设法做到这一点?
我知道如何通过eval
和parse
的组合来实现这一点,但这真的很慢:
eval
所以我转向foo <- function(idx, obj = character(), sep = c("[['", "']][['", "']]")) {
out <- paste0(sep[1], paste(idx, collapse = sep[2]), sep[3])
if (length(obj)) {
out <- paste0(obj, out)
}
out
}
> foo(c("a", "b"), "x")
[1] "x[['a']][['b']]"
expr <- parse(text = foo(c("a", "b"), "x"))
> expr
expression(x[['a']][['b']])
> eval(expr)
[1] 1
。虽然这对于我想要编写R表达式的大多数任务都很好,但我不知道如何使用它来进行这种&#34;嵌套提取&#34;任务:
substitute
这是计算成本的比较:
expr <- substitute(assign(X, VALUE),
list(X = "x_2", VALUE = as.name("letters")))
> expr
assign("x_2", letters)
eval(expr)
> x_2
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u"
[22] "v" "w" "x" "y" "z"
expr <- substitute(FUN(X, INDEX),
list(FUN = as.name('[['), X = as.name("x"), INDEX = "a"))
> expr
x[["a"]]
> eval(expr)
$b
[1] 1
我提出了一个可以利用# install.packages("microbenchmark")
require(microbenchmark)
res <- microbenchmark(
"1" = {
expr <- substitute(assign(X, VALUE),
list(X = "x_2", VALUE = as.name("letters")))
eval(expr)
},
"2" = {
expr <- substitute(FUN(X, INDEX),
list(FUN = as.name('[['), X = as.name("x"), INDEX = "a"))
eval(expr)
},
"3" = {
expr <- parse(text = foo(c("a", "b"), "x"))
eval(expr)
}
)
> res
Unit: microseconds
expr min lq mean median uq max neval
1 3.519 4.1060 6.12306 4.839 5.7185 59.528 100
2 2.639 3.5190 4.41350 4.105 4.6920 20.820 100
3 196.765 204.6825 220.33854 212.600 222.8630 505.547 100
的功能,同时也可以完成处理递归方面的任务:
substitute
然后Gabor得出了他的答案,让我意识到我认为由于一些无法解释的原因,我之前从未使用bar <- function(idx, obj) {
for (ii in 1:length(idx)) {
if (ii == 1) {
X <- as.name("obj")
} else {
X <- expr
}
INDEX <- idx[ii]
expr <- substitute(FUN(X, INDEX),
list(FUN = as.name('[['), X = X, INDEX = INDEX))
}
expr
}
多个索引值。我只对[[
这样做了。有点尴尬;-)。不过,这里是综合比较:
[
答案 0 :(得分:2)
使用问题中的x
尝试此操作:
x[[c("a", "b")]]
## [1] 1