Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

patterns only looks in the global environment for variables #1749

Closed
kendonB opened this issue Jun 22, 2016 · 2 comments
Closed

patterns only looks in the global environment for variables #1749

kendonB opened this issue Jun 22, 2016 · 2 comments

Comments

@kendonB
Copy link

kendonB commented Jun 22, 2016

Using a previously defined variable inside patterns fails when done inside a user-written function.

require(data.table)
DT <- data.table(
  i_1 = c(1:5, NA), 
  i_2 = c(NA,6,7,8,9,10), 
  f_1 = factor(sample(c(letters[1:3], NA), 6, TRUE)), 
  f_2 = factor(c("z", "a", "x", "c", "x", "x"), ordered=TRUE), 
  c_1 = sample(c(letters[1:3], NA), 6, TRUE), 
  d_1 = as.Date(c(1:3,NA,4:5), origin="2013-09-01"), 
  d_2 = as.Date(6:1, origin="2012-01-01"))
# add a couple of list cols
DT[, l_1 := DT[, list(c=list(rep(i_1, sample(5,1)))), by = i_1]$c]
DT[, l_2 := DT[, list(c=list(rep(c_1, sample(5,1)))), by = i_1]$c]

# NEW FEATURE: measure.vars can be a list
# melt "f_1,f_2" and "d_1,d_2" simultaneously, retain 'factor' attribute
# convenient way using internal function patterns()
tmp <- function(dt){
  patt <- c("^f_", "^d_")
  melt(dt, id=1:2, measure=patterns(patt), value.factor=TRUE)
}
tmp(DT)
# Error in unlist(list(...), use.names = FALSE) : object 'patt' not found 
@jangorecki
Copy link
Member

@kendonB Did you read ?data.table::patterns?

@franknarf1
Copy link
Contributor

franknarf1 commented Jun 22, 2016

@jangorecki Even knowing what's written there, I think what they're asking for is a reasonable FR. (Not sure if you meant something else by posting that link.)

The feature is for convenience, but is not yet convenient to use programmatically. Looking at melt, I guess this would just require tweaking the environment of the eval(measure.sub) call somehow... or just not evaling it at all?

As a workaround, the OP could recreate the behavior of patterns:

tmp <- function(dt){
    patt <- c("^f_", "^d_")
    melt(dt, id=1:2, measure=lapply(patt, grep, names(dt)), value.factor=TRUE)
} 
tmp(DT)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants