Object not found for lapply data.table inside function

Suppose I have the following R code:

library(data.table)
L <- list(a=data.table(x=c(1,2,3),y=c(10,20,30)),
          b=data.table(x=c(4,5,6),y=c(40,50,60)),
          c=data.table(x=c(7,8,9),y=c(70,80,90)))


columnName <- "x"         
r <- lapply(L,"[",i=get(columnName) %in% c(1,4))

f <- function(L1) {
     columnName1 <- "x"
     r1 <- lapply(L1,"[",i=get(columnName1) %in% c(1,4))
     return(r1)
}

r1 <- f(L)

My question is: why does the assignment of r1 at the bottom end inside the function with

Error in get (columnName1): object 'columnName1' not found

Approach to work stops. Similarly, if inside the function I change it to a global destination for columnName1 via <<-, but then I created a global variable that I really don't want .... How can I cleanly rewrite this so that data.table finds columnName1 in your area? And what am I missing in the field of view? I would have thought that if he could not find columnName1 in the "[" function, he would look in one environment "up" and find it there? Should it look in a global environment, but not in a parent?

+4
2

, data.table. , x 1 4, , lapply

library(data.table)
columnName1 <- "x"
L$a[get(columnName1) %in% c(1,4)]

lapply(L, function(x) x[get(columnName1) %in% c(1,4)])

,

f <- function(list, col, row) {lapply(list, function(x, lcol, lrow) x[get(lcol) %in% lrow], lcol=col, lrow=row)}
f(L, "x", c(1,4))
0

lapply , , , , - , . , get(), , data.table(), . - , , get [.data.table.

f <- function(L1) {
     columnName1 <- "x"
     r1 <- lapply(L1, function(x) x[i=get(columnName1) %in% c(1,4)])
     r1
}

r1 <- f(L)

r1
#$a
#   x  y
#1: 1 10

#$b
#   x  y
#1: 4 40

#$c
#Empty data.table (0 rows) of 2 cols: x,y

, , , data.table .

0

Source: https://habr.com/ru/post/1664482/


All Articles