gpt4 book ai didi

r - 为什么我需要将 `get` 包装在 J `lapply` 调用中的虚拟函数中?

转载 作者:行者123 更新时间:2023-12-04 02:49:30 25 4
gpt4 key购买 nike

我希望通过 grep 按类别或常见模式匹配等标准处理列。

我的第一次尝试没有成功:

require(data.table)
test.table <- data.table(a=1:10,ab=1:10,b=101:110)
##this does not work and hangs on my machine
test.table[,lapply(names(test.table)[grep("a",names(test.table))], get)]

Ricardo Saporta notes in an answer你可以使用这个构造,但你必须将 get 包装在一个虚拟函数中:

##this works
test.table[,lapply(names(test.table)[grep("a",names(test.table))], function(x) get(x))]

为什么需要匿名函数?

(首选/更清洁的方法是通过 .SDcols:)

test.table[,.SD,.SDcols=grep("a",names(test.table))]
test.table[, grep("a", names(test.table), with = FALSE]

最佳答案

虽然@Ricardo 是正确的,将依赖于方法分派(dispatch)的基元或函数包装在包装器中更安全,但在这里我们可以通过设置正确的 environment 来避免这种情况。对于 get在其中搜索。 lapply 的技巧就是用sys.parent(n) (在这种情况下 n = 0 将起作用)以获得适当的调用环境。

test.table[,lapply(grep('a',names(test.table),value=TRUE), 
get, envir = sys.parent(0))]

(更多信息可以在这里找到Using get inside lapply, inside a function)

关于r - 为什么我需要将 `get` 包装在 J `lapply` 调用中的虚拟函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18064602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com