Home > Back-end >  Calculating fraction, which is in column as string
Calculating fraction, which is in column as string

Time:02-02

I have a data.frame like this

z <- structure(list(ID = c("R-HSA-977606", "R-HSA-977443", "R-HSA-166658", 
"R-HSA-166663", "R-HSA-1236394", "R-HSA-390522", "R-HSA-3232118", 
"R-HSA-1630316", "R-HSA-112315", "R-HSA-112314"), GeneRatio = c("6/189", 
"6/189", "6/189", "4/189", "5/189", "4/189", "3/189", "7/189", 
"11/189", "9/189")), row.names = c("R-HSA-977606", "R-HSA-977443", 
"R-HSA-166658", "R-HSA-166663", "R-HSA-1236394", "R-HSA-390522", 
"R-HSA-3232118", "R-HSA-1630316", "R-HSA-112315", "R-HSA-112314"
), class = "data.frame")

Is it possible to add a 3rd column with the ratio from the 2nd column calculated? i.e. 6/189=0.0317. So in the third column I should have 0.0317.

CodePudding user response:

As it is a string expression, we can use eval/parse

z$newColumn <- sapply(z$GeneRatio, function(x) eval(parse(text = x)))

-output

> z
                         ID GeneRatio  newColumn
R-HSA-977606   R-HSA-977606     6/189 0.03174603
R-HSA-977443   R-HSA-977443     6/189 0.03174603
R-HSA-166658   R-HSA-166658     6/189 0.03174603
R-HSA-166663   R-HSA-166663     4/189 0.02116402
R-HSA-1236394 R-HSA-1236394     5/189 0.02645503
R-HSA-390522   R-HSA-390522     4/189 0.02116402
R-HSA-3232118 R-HSA-3232118     3/189 0.01587302
R-HSA-1630316 R-HSA-1630316     7/189 0.03703704
R-HSA-112315   R-HSA-112315    11/189 0.05820106
R-HSA-112314   R-HSA-112314     9/189 0.04761905

Or a faster option would be to split by / (or use read.table to create two columns and then divide (assuming the expression includes only division)

z$newColumn <- Reduce(`/`, read.table(text = z$GeneRatio, 
    header = FALSE, sep = "/"))

CodePudding user response:

This code could be refined but it will work with the eval function

# 1- Creating empty column
z$GeneRatioNum <- NA

# 2- Filling it with eval function
for(i in 1:nrow(z)){z$GeneRatioNum[i] <- (eval(parse(text = z$GeneRatio[i])))}
  •  Tags:  
  • Related