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 to r1 at the bottom fail inside the function with
Error in get(columnName1) : object 'columnName1' not found
The assigment to r further up works fine. Likewise, if, inside the function I change it to a global assignment for columnName1 via <<-, but then I have created a global variable which I don't really want.... How can I cleanly rewrite this such that data.table finds columnName1 within its scope? And what am I missing about scoping? I would have thought that if it can't find columnName1 within the "[" function it will look one environment "up" and find it there? It must look in the global environment though, but not in the parent?
I'm guessing slight what you're looking to return from the data.table
. If you're looking to return rows where column x
equals 1 and 4 it's usually easier to get it to work with a single value from the list and then get it to work with lapply
library(data.table)
columnName1 <- "x"
L$a[get(columnName1) %in% c(1,4)]
to iterate through the list
lapply(L, function(x) x[get(columnName1) %in% c(1,4)])
if you want a function that can specify the column name and row numbers
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With