本文介绍了为什么我需要在一个J`lapply`调用中的一个虚函数中包装`get`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要通过类别或通过 grep 的常见模式匹配的标准来处理列。



我的第一次尝试无效:

  require table)
test.table< - data.table(a = 1:10,ab = 1:10,b = 101:110)
##这不工作,挂在我的机器上
test.table [,lapply(names(test.table)[grep(a,names(test.table))],get)]

,你可以使用这个结构,但你必须换行 get 在一个虚函数:

  ## this works 
test.table [,lapply name(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]


解决方案

这是 lapply 的函数,不是真的 data.table lapply 文档:


()函数必须在R 2.7.1中使用了lapply(ll,function(x)is.numeric(x)),才能确保is.numeric的方法调度正确。

更新re @ Hadley和@ DWin的意见:



  EE  EE $ var2<  - 我是EE中的var2

##直接调用
(f(var1,var2)[[1L]],...)中出现错误:object(c:var1,var2), 'var1'not found

##通过匿名函数调用
with(EE,lapply(c(var1,var2),function(x)get(x) ))
[[1]]
[1]I is var1 in EE

[[2]]
[1] EE






 与(EE,lapply(c(var1,var2),rm))
在FUN(c(var1,var2)[[1L]],...)
...必须包含名称或字符串

with(EE,lapply(c(var1,var2),function(x)rm(x)))
[[1]]
NULL

[[2]]
NULL

#var1& var2现在已被删除
EE
< environment:0x1154d0060>


I'm looking to process columns by criteria like class or common pattern matching via grep.

My first attempt did not work:

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 that you can use this construct, but you have to wrap get in a dummy function:

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

Why do you need the anonymous function?

(The preferred/cleaner method is via .SDcols:)

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

This is a function of lapply, not really data.table From the lapply documentation:

Update re @Hadley's and @DWin's comments:

EE <- new.env()
EE$var1 <- "I am var1 in EE"
EE$var2 <- "I am var2 in EE"

## Calling get directly
with(EE, lapply(c("var1", "var2"), get))
Error in FUN(c("var1", "var2")[[1L]], ...) : object 'var1' not found

## Calling get via an anonymous function
with(EE, lapply(c("var1", "var2"), function(x) get(x)))
[[1]]
[1] "I am var1 in EE"

[[2]]
[1] "I am var2 in EE"


with(EE, lapply(c("var1", "var2"), rm))
Error in FUN(c("var1", "var2")[[1L]], ...) :
  ... must contain names or character strings

with(EE, lapply(c("var1", "var2"), function(x) rm(x)))
[[1]]
NULL

[[2]]
NULL

# var1 & var2 have now been removed
EE
<environment: 0x1154d0060>

这篇关于为什么我需要在一个J`lapply`调用中的一个虚函数中包装`get`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 09:01