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?
1 answer
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
Log in to answer this question.