CPak
CPak

Reputation: 13591

R ls(pattern=...) programmatically within sapply

I can't get the following to work.

I create 6 variables A_N and B_N where N=1:3. I want to grab values from namespace using a numeric vector and sapply. Outside sapply, ls(pattern=paste0(...)) seems to work. But within sapply, it fails.

rm(list=ls())
A_1 <- letters[1]
A_2 <- letters[1]
A_3 <- letters[1]
B_1 <- letters[1]
B_2 <- letters[1]
B_3 <- letters[1]
ls()
# [1] "A_1" "A_2" "A_3" "B_1" "B_2" "B_3"

N <- c(1, 2)

ls(pattern=paste0("A_", 1))
# [1] "A_1"

sapply(N, function(i) ls(pattern=paste0("A_", i)))
# [[1]]
# character(0)

# [[2]]
# character(0)

Any help is appreciated!

Upvotes: 1

Views: 327

Answers (1)

Florian
Florian

Reputation: 25415

I think this has to do with the fact that sapply functions run in their own environment, you can get the parent environment as follows:

sapply(N, function(i) ls(pattern=paste0("A_", i),envir=parent.env(environment())))

Output:

[1] "A_1" "A_2"

Hope this helps!

Upvotes: 4

Related Questions