-1

Is there any way to use a loop to write this code? Each line of code is identical except from the species name

ensembl_hsapiens <- useMart("ensembl", 
                        dataset = "hsapiens_gene_ensembl")
ensembl_mouse <- useMart("ensembl", 
                     dataset = "mmusculus_gene_ensembl")
ensembl_chicken <- useMart("ensembl",
                       dataset = "ggallus_gene_ensembl")
Jack Dean
  • 163
  • 1
  • 7
  • 1
    `lapply(setNames(, c("hsapiens", "mmusculus", "ggallus")), function(x) useMart("ensembl", dataset = sprintf("%s_gene_ensembl", x)))` maybe. – Frank Apr 25 '18 at 15:40

1 Answers1

2

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"]]

ngm
  • 2,539
  • 8
  • 18