How to map gene names to ensembl Ids in R

I am trying to convert a list of gene names into Ensembl IDs but I'm having a bit of trouble.

I've tried using the EnsDb.Hsapiens.v86 package but I always get LRG-ID values returned as well, even when using the GeneIdFilter "startsWith" thing.
My code looks like this:

targets <- as.character(targetCSV[, 2])

targetEnsemble <- ensembldb::select(
EnsDb.Hsapiens.v86,
filter = GeneIdFilter("ENS", "startsWith"),
keys = targets,
keytype = "SYMBOL",
columns = c("SYMBOL","GENEID"))


And for example I get back:

    SYMBOL          GENEID
1     CYR61 ENSG00000142871
2      CTGF ENSG00000118523
3    AMOTL2 ENSG00000114019
4    ANKRD1 ENSG00000148677
5    ANKRD1         LRG_379
6    IGFBP3 ENSG00000146674
7        F3 ENSG00000117525


I also tried using org.Hs.eg.db package but get a different problem where some of my genes return NA.

My code:

  mapIds(x = org.Hs.eg.db,
keys = targets,
"ENSEMBL",
"SYMBOL",
fuzzy = TRUE,
multiVals = first)


And this works on some but not all the genes for some reason.

    $CYR61 [1] NA$CTGF
[1] NA

$AMOTL2 [1] "ENSG00000114019"$ANKRD1
[1] "ENSG00000148677"

$IGFBP3 [1] "ENSG00000146674"$F3
[1] "ENSG00000117525"


If anyone can solve either of these problems that would be great, thanks in advance!

• Have you considered just downloading a list of gene IDs and the associated gene names from Ensembl Biomart? Apr 24 '20 at 13:54
• Yeah but I wanted to be able to change out the genesets quickly and this just added another annoying step Apr 24 '20 at 14:08
• There's an R package to allow fetching those programmatically from biomart. Apr 24 '20 at 14:21

library(biomaRt)

You do not find some genes in your example because you were not using the official gene name. For example CTGF is offocially called CCN2 and with this name you will find the appropriate Ensembl gene ID in the biomaRt table. This is why I personally prefer to use gene name that are like ENSG00000118523|CCN2 in my work. That way you always have a unique identifier (the Ensembl ID) that is unambiguous and you do not run into trouble that for one gene many more or less official gene names exist.