Here's an approach. Note that using a loop (or a loop-equivalent construct) to populate the global environment isn't often a good idea. But it's what you asked for.
There's nothing special about useMart
, so I'll make up a nonsense function that takes two character arguments:
foo <- function(x, y) {
nchar(paste(x, y))
}
Here are the species names. I'll use them for the object names as well.
species <- c("hsapiens", "mmusculus", "ggallus")
Now, you want to create three named objects in the global environment. You can use the assign
function for this, noting that you use pos=2
because each loop of lapply
is done in its own environment.
lapply(species, function(s) assign(paste0("ensembl_", s),
foo("ensemble", paste0(s, "_gene_ensembl")),
pos = 1))
This gives you what you want. You can replace foo
use useMart
.
Now, is this a good idea? Perhaps not. I would be more inclined to keep the objects themselves in a list.
objs <- lapply(species, function(s) foo("ensemble", paste0(s, "_gene_ensembl")))
names(objs) <- paste0("ensemble_", species)
You can access them using statements like objs$ensemble_hsapiens
or objs[["ensemble_hsapiens"]]