mnal
mnal

Reputation: 47

R: fraction of class character to decimal - other approachs don't work

sorry for the duplicate, but for some reason, the answer shown here doesn't work for me. I´ve checked and the data table I'm working with is of character nature.

That's my data table

> dt <- data.table(V1 = c("4", "1", "0", "3"), V2 = c("0/1", "0/1", "1/2", "3/4"))

> dt
   V1  V2
1:  4 0/1
2:  1 0/1
3:  0 1/2
4:  3 3/4

> class(dt)
[1] "data.table" "data.frame"
> class(dt$V2)
[1] "character"

As you see I modeled the second column so as to have elements exclusively in fraction format. I want to have the second column in decimal format, the first column as a numeric rather than character & the final objective is to have the two columns summed up row-wise.

As I try turning it to decimal however it has no effect whatsoever on my dt - see it for yourselves

> FractionToDecimal <- function(x) {
+   eval(parse(text=as.character(x)))
+        x
+ }
> sapply(dt$V2, FractionToDecimal)
  0/1   0/1   1/2   3/4 
"0/1" "0/1" "1/2" "3/4" 
> FractionToDecimal(dt$V2)
[1] "0/1" "0/1" "1/2" "3/4"

The other approach I used, also doesn't work out

> dt %>% mutate(V2 = eval(parse(text = V2)))
  V1   V2
1  4 0.75
2  1 0.75
3  0 0.75
4  3 0.75

It just repeats the wrong result all over.

Does someone know where the problem lies?

If someone also knows how to have both columns turned into numeric/integer format afterward, it would also be of help!!

Thank you!!

Upvotes: 0

Views: 285

Answers (3)

akrun
akrun

Reputation: 887223

Another option is to split with tstrsplit and divide

library(data.table)
dt[, do.call(`/`, tstrsplit(V2, "/", type.convert =TRUE))]
#[1] 0.00 0.00 0.50 0.75

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389047

Your function works but you are not changing x in the function and returning an unchanged x.

So either return output of eval + parse directly

FractionToDecimal <- function(x) eval(parse(text=x))
sapply(dt$V2, FractionToDecimal, USE.NAMES = FALSE)
#[1] 0.00 0.00 0.50 0.75

Or store the result in x and return the changed x.

FractionToDecimal <- function(x) {
   x <- eval(parse(text=x))
   x
}

sapply(dt$V2, FractionToDecimal, USE.NAMES = FALSE)
#[1] 0.00 0.00 0.50 0.75

Upvotes: 1

jay.sf
jay.sf

Reputation: 72984

Use sapply.

dt$V2 <- sapply(dt$V2, function(x) eval(parse(text=x)))
dt
#   V1   V2
# 1  4 0.00
# 2  1 0.00
# 3  0 0.50
# 4  3 0.75

Upvotes: 1

Related Questions