How to convert a value of columnA to a value of columnB (in R)?
1
0
Entering edit mode
3.7 years ago

Hi all,

I am having a trouble using R. I want to make a function for converting IDs between two ID formats using R.

From the file (below),

"idConverion.txt"

gene_name gene_id

AB ENSG001

ABC ENSG002

WER ENSG0052

and the function I defined below,

geneConv <- function(input, output) {

df <- fread("idConversion.txt")

input <- df$gene_name

output <- df$gene_id

return(output)

}

I want to get this result.

geneConv("AB")

"ENSG001"

But with this function, I could only get all of the IDs of column B. Could someone help me with this?

R • 538 views
ADD COMMENT
0
Entering edit mode
3.7 years ago

Replace test.txt with input.txt.

library(data.table)
geneConv <- function(x) {
    df <- fread("test.txt")
    output=df[gene_name==x,.(gene_id)]
    return(output)
}
geneConv("AB")

See if you can take fread function out. This is because every time, you want to search a gene ID, it has to execute fread and this affects the performance. Try something like this:

df <- fread("test.txt")
geneConv <- function(x) {
    output=df[gene_name==x,.(gene_id),nomatch=NA]
    return(output)
}

however, I would suggest to use this:

geneConv <- function(x) {
+     output=df[gene_name %in% x ,.(gene_id)]
+     return(output)
+     }
> 
> geneConv(c("AB","CD","ABC"))
   gene_id
1: ENSG001
2: ENSG002
ADD COMMENT

Login before adding your answer.

Traffic: 1964 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6