Why does lapply() not retain my data.table keys?

☆樱花仙子☆ 提交于 2019-12-03 11:49:58

Interestingly, notice the difference between these two different results

lapply(dt.list, unique) 
lapply(dt.list, function(x) unique(x)) 

If you use the latter, the results are as you would expect.


The seemingly unexpected behavior is due to the fact that the first lapply statement is invoking unique.data.frame (ie from {base}) while the second is invoking unique.data.table

Good question. It turns out that it's documented in ?lapply (see Note section) :

For historical reasons, the calls created by lapply are unevaluated, and code has been written (e.g. bquote) that relies on this. This means that the recorded call is always of the form FUN(X[[0L]], ...), with 0L replaced by the current integer index. This is not normally a problem, but it can be if FUN uses sys.call or match.call or if it is a primitive function that makes use of the call. This means that it is often safer to call primitive functions with a wrapper, so that e.g. lapply(ll, function(x) is.numeric(x)) is required in R 2.7.1 to ensure that method dispatch for is.numeric occurs correctly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!