Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid first argument in get when using data.table in lapply

Here is a data.table and a function minmax returning a list:

library(data.table)
DT = data.table(
  x = c(1.59631745098427, -1.82698333087074, -1.69796526239799, 
        -0.69409651665197, 0.360640961221989), 
  y = c(-2.11104985109763, -1.49347081392737, 1.49801321753262,
        -0.736044012256148, 1.68957962245701), 
  Factor1 = c("a", NA, "a", "a", "a"), 
  Factor2 = c("UU", "UU", "UU", "UU", "UU"), 
  Factor3 = c("GHI", "GHI", "DEF", "ABC", "DEF"), 
  x_FACTOR = c("(1,2]", "(-2,-1]", "(-2,-1]", "(-1,0]", "(0,1]"),
  y_FACTOR = c("(-3,-2]", "(-2,-1]", "(1,2]", "(-1,0]", "(1,2]"), 
  Factor1_FACTOR = c("a", NA, "a", "a", "a"),
  Factor2_FACTOR = c("UU", "UU", "UU", "UU", "UU"), 
  Factor3_FACTOR = c("GHI", "GHI", "DEF", "ABC", "DEF")
)

minmax <- function(x) list(min = min(x), max = max(x))

names(DT)
# [1] "x"              "y"              "Factor1"        "Factor2"        "Factor3"       
# [6] "x_FACTOR"       "y_FACTOR"       "Factor1_FACTOR" "Factor2_FACTOR" "Factor3_FACTOR"

I can do:

DT[, minmax(get("x"))]
#          min      max
# 1: -1.826983 1.596317

But within lapply I get an error:

lapply(c("x", "y"), function(x) DT[, minmax(get(x))])
#  Error in get(x) : invalid first argument

The very strange thing is that this comes from a Shiny app where the dataset is uploaded, and for other datasets I don't get this error.


EDIT

I've just observed that this works like this:

lapply(c("x", "y"), function(u) DT[, minmax(get(u))])

Any explanation would be welcome.

like image 351
Stéphane Laurent Avatar asked Jun 05 '26 19:06

Stéphane Laurent


1 Answers

The problem is that there's a column named x, so scoping means x the column is found before x the argument from lapply. You can observe this like so:

lapply(c("x", "y"), function(x) DT[, minmax({dput(x); get(x)})])
# c(1.59631745098427, -1.82698333087074, -1.69796526239799, -0.69409651665197, 0.360640961221989)
like image 167
MichaelChirico Avatar answered Jun 08 '26 10:06

MichaelChirico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!