jO.
jO.

Reputation: 3512

probe global variables to call inside function

I want to pass variables within the .Globalenv when inside a function. Basically concatenate x number of data frames into a matrix.

Here is some dummy code;

Alpha <- data.frame(lon=124.9167,lat=1.53333)

Alpha_2 <- data.frame(lon=3.13333, lat=42.48333)

Alpha_3 <- data.frame(lon=-91.50667, lat=27.78333)

myfunc <- function(x){
     vars <- ls(.GlobalEnv, pattern=x)
     mat <- as.matrix(rbind(vars[1], vars[2], vars[3]))
     return(mat)
}

When calling myfunc('Alpha') I would like the same thing to be returned as when you run;

as.matrix(rbind(Alpha, Alpha_2, Alpha_3)

        lon      lat
1 124.91670  1.53333
2   3.13333 42.48333
3 -91.50667 27.78333

Any pointers would be appreciated, thanks!

Upvotes: 2

Views: 101

Answers (1)

BrodieG
BrodieG

Reputation: 52667

You can use get to retrieve variables by name. We do this here in a loop with lapply, and then use rbind to bind them together.

myfunc <- function(x){
  vars <- ls(.GlobalEnv, pattern=x)
  df <- do.call(rbind, mget(vars, .GlobalEnv))  # courtesy @Roland
  return(df)
}
myfunc("Alpha")

#         lon      lat
# 1 124.91670  1.53333
# 2   3.13333 42.48333
# 3 -91.50667 27.78333

Note, in practice, you probably want to check that the variables that match the pattern actually are what you think they are, but this gives you the rough tools you want.

Old version (2nd line of func):

df <- do.call(rbind, lapply(vars, get, envir=.GlobalEnv))

Upvotes: 2

Related Questions