The object disappears from the namespace in the function

I am writing a wrapper to combine any number of data sets in a row. Since some may have unique variables, I first restrict the variables in the data.

My function works as follows

rcombine <- function(List, Vars) { List2 <- lapply(List, subset, select=Vars) Reduce(rbind, List2) } 

When I run the code directly, it works. But in the function, my Vars variable disappears.

For instance:

 x <- data.frame('a'=sample(LETTERS, 10), 'b'=sample(LETTERS, 10), 'c'=sample(LETTERS, 10)) y <- data.frame('a'=sample(LETTERS, 10), 'b'=sample(LETTERS, 10), 'e'=sample(LETTERS, 10)) rcombine(list(x, y), c('a', 'b')) 

gives me:

 Error in eval(expr, envir, enclos) : object 'Vars' not found 

but it works:

 List <- list(x, y) Reduce(rbind, lapply(List, subset, select=c('a','b'))) 

Works. I can print Vars from a function, but inside lapply it disappears. What's happening?

+1
source share
1 answer

subset really should not be used for these types of things. On the help page

This is a convenience feature designed for interactive use. For programming, it is better to use standard subset functions, such as [and, in particular, non-standard evaluation of a subset of arguments can have unforeseen consequences.

For your specific problem, I don’t understand why just replacing a subset with "[" would be a problem.

 rcombine <- function(List, Vars) { List2 <- lapply(List, "[", i= , j = Vars, drop = FALSE) # here is the change Reduce(rbind, List2) } # alternatively... rcombine <- function(List, Vars) { List2 <- lapply(List, function(x){x[, Vars, drop = FALSE]}) # here is the change Reduce(rbind, List2) } x <- data.frame('a'=sample(LETTERS, 10), 'b'=sample(LETTERS, 10), 'c'=sample(LETTERS, 10)) y <- data.frame('a'=sample(LETTERS, 10), 'b'=sample(LETTERS, 10), 'e'=sample(LETTERS, 10)) rcombine(list(x, y), c('a', 'b')) 
+4
source

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


All Articles