-1

I have a column in my data frame df called Ratio which comprises of two positive integers x and y separated by a / [That is, format the is x/y]. I would like to replace each row in this column by integer((x/y)*10) (rounded off to the nearest integer)

Example, if that value of an element in Ratio is 14/20 I need to change it to 7.

[There is a level 0/0 in the Ratio column in which case I would like it changed to 5]

3 Answers3

0
df$Ratio<-as.character(df$Ratio)
df$resRatio[df$Ratio!="0/0"]<-sapply(df$Ratio[df$Ratio!="0/0"],
                                     function(expr) {
                                           round(eval(parse(text=expr))*10,0)})
df$resRatio[df$Ratio=="0/0"]<-5
Cath
  • 23,906
  • 5
  • 52
  • 86
0

Here's an approach:

# an example data frame
> dat <- data.frame(Ratio = c("0/0", "14/20"))

transform(dat, Ratio2 = sapply(strsplit(as.character(Ratio), "/"), function(x) 
  if (x[2] == "0") 5 else round(Reduce("/", as.integer(x)) * 10)))
#   Ratio Ratio2
# 1   0/0      5
# 2 14/20      7
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • Hey this one is good too. Actually I like this one better because it separates the numbers individually which I suddenly happen to need. – moonshinebutter Oct 29 '14 at 19:09
-1

Have you tried to use as.integer?

> as.integer(14.001/20.01*10)
[1] 7
Henrik
  • 3,714
  • 1
  • 18
  • 20
  • 1
    What `as.integer` has to do with anything here? What just `14/20*10` gives you? I also toubt he has `14/20` in his `Ratio` column, otherwise R would transfer it to `0.7` – David Arenburg Oct 28 '14 at 12:03