r - convert slash to division -


i have column of type character looks (1/1), (2/3), (4/5) etc.

i convert vector 1, 0.66, 0.80 etc.

is there simple way this?

the way think of like

pseudocode

separate string delimited slash, part[1] , part[2] part[1] = as.integer(part[1]) part[2] = as.integer(part[2]) score = part[1]/part[2]  

edit : data looks follows

> df[1:10,"score"]  [1] "1/1" "1/1" "3/3" "1/1" "1/1" "4/4" "1/1" "2/2" "4/5" "4/5" > class(df$score) [1] "character" 

assuming data

x <- c("1/1", "1/1", "3/3", "1/1", "1/1", "4/4", "1/1", "2/2", "4/5", "4/5") 

using read.table

with(read.table(text = x, sep = "/"), v1 / v2) ## [1] 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.8 0.8 

or per @akruns comment, using scan

temp <- scan(text = x, = numeric(), sep = "/", quiet = true) temp[c(true, false)]/temp[c(false, true)] ## [1] 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.8 0.8 

or using strsplit

temp <- as.numeric(unlist(strsplit(x, "/"))) temp[c(true, false)]/temp[c(false, true)] ## [1] 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.8 0.8    

or

library(gsubfn) as.numeric(gsubfn("([0-9]+)/([0-9]+)", ~ as.numeric(x)/as.numeric(y), x)) ## [1] 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.8 0.8         

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -