R: How to set values in empty column based on condition of another column?

Viewed 46

I am trying to write a function that will check to see if each value in a vector is greater than a certain value, and will then initialize a different empty column to 1 or 0. If the value is greater than the set parameter, then the same index of the empty column will be set to 1. Otherwise if it isn't greater than that number, it will be set to 0. So my function will take in a value, column containing probabilities, and then another column that is empty which will later be made into a column of 1's and 0's.

I don't get any errors when running the function however that empty column does not get updated.

I feel like my logic is right but clearly something is not working.

cut_off_prob <- function(x, prob, pred_class) {
  for (i in 1:length(prob))
  {
    if(prob[i] > x)
    {
     pred_class[i] <- 1
    }
      else {
     pred_class[i] <- 0
    }
  }
}
1 Answers

There is no need of pred_class as a function parameter. Try this:

cut_off_prob <- function(x, prob) {
  pred_class <- c() # initialize as an empty vector
  for (i in 1:length(prob)){
    if(prob[i] > x){pred_class[i] <- 1}
    else {pred_class[i] <- 0}
  }
return(pred_class)
}

By the other hand, i strongly recommend you not to use for loops in this case, since as @Gregor Thomas said it's very inefficient. In comparison, check this:

pred_class <- rep(0,length(prob));
pred_class[prob>x] <- 1

Running time is shown here (in seconds):

"Loop Time: 0.0029909610748291 Conditional Indexing Time: 0.000996828079223633"
Related