Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behaviour when piping to ls() in R?

Tags:

r

This returns the name of every second object in the environment

test <- ls()
c(FALSE, TRUE) %>% { test[.] }

But this doesn't (it produces a strange vector of NAs)

c(FALSE, TRUE) %>% { ls()[.] }

Why doesn't the second method work?

like image 743
stevec Avatar asked Aug 07 '19 16:08

stevec


1 Answers

It looks like ls() can't "figure out" the current environment when it is called in a pipe. When you assign the ls() outside of a pipe, then call the vector explicitly, there is no searching for the environment. To get around this, just explicitly call the environment in ls().

c(FALSE, TRUE) %>% ls(envir = .GlobalEnv)[.]
like image 194
AndS. Avatar answered Nov 15 '22 04:11

AndS.