1

I would like to calculate a ratio (A / B = C). Then I want to assign a label for ratio. If the ratio equals 0 label gets "0". If value less than 1 label gets "1". Lastly ratio is greater than 1 label gets "2".

Here is the example data:

                    A            B         C
  1                 0        171.06  0.0000000
  2                 1             2  0.5
  3                 0        120.84  360.00000
  4                 0        308.07  0.0000000
  5                 0        243.06  0.0000000
  6                 0       876.015  0.0000000

Here is the function with loop:

targets <- function(data)
{
  label_df <- data[,c("A", "B")]
    label_df[is.na(label_df)] <- 0
    label_df["C"] <- (label_df["A"] / label_df["B"]) 
    for(i in 1:nrow(label_df))
    {
      if(label_df$C == 0){label_df[i,"C"] <- 0}

       else if(label_df$C < 1){label_df[i,"C"] <- 1}
       else {label_df[i,"C"] <- 2}
      }
return(as.data.frame(label_df))
    }

And here is the result. It shows all labels 0.

lab <- target(data)      
head(lab)      

                    A            B         C      label     
  1                 0        171.06  0.0000000    0
  2                 1             2  0.5          0
  3                 0        120.84  360.00000    0
  4                 0        308.07  0.0000000    0
  5                 0        243.06  0.0000000    0
  6                 0       876.015  0.0000000    0

I check the result with table() function and it just shows all data for label 0. There are no 1 or 2 labels. I couldn't figure out where the problem is. Any idea?

3 Answers3

2

We can do this with cut

df1$label <- cut(df1$C, breaks = c(-Inf,0, 1, Inf), labels = c(0, 1, 2))

Or with findInterval

findInterval(df1$C, c(0, 1, Inf), left.open = TRUE)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    So I was trying to solve the problem with a very hard way. Thanks for this very easy solution! Next time I will think simple firstly... – silverstone Jun 12 '17 at 07:46
1
df$D=ifelse(df$C<=1,1,2)

df$D=ifelse(df$C==0,0,df$D)
Ajay Ohri
  • 3,382
  • 3
  • 30
  • 60
0

I strongly recommend you to learn the ifelse function. You can nest it and obtain vectors following complex conditional statements. For your example I'd use something like:

ifelse ( ratio == 0, 0, ifelse (ratio < 1, 1,2))
elcortegano
  • 2,444
  • 11
  • 40
  • 58
  • Yeah I thought the ifelse function but I have 3 labels. So I couldn't figure out how can I use if else situation for 3 labels. Maybe it could be nested but like I said: I couldn't figure out! Thanks for the answer. – silverstone Jun 12 '17 at 07:50