1

I am trying to categorize FICO scores in three categories and want to create a new column where the corresponding value can be displayed.

My data:

FICO
650
450
700

Expected output

FICO    Category
650     Moderate
450     Poor
700     Excellent

I wrote an if statement for this

model_data$ficocategory <- if (model_data$FICO>=350 && 
model_data$FICO<=500) {
print("POOR")
  } else if (model_data$FICO>=501 && model_data$FICO<=650) {
print("MODERATE")
  } else
    print("EXCELLENT")

But the output I get is

[1] "MODERATE"
  • `&&` isn't vectorized. Use `&`. – John Coleman Apr 05 '18 at 01:04
  • @JohnColeman if i use only '&' it gives output as [1] "EXCELLENT" –  Apr 05 '18 at 01:05
  • If you want to create a vector -- you should also use the `ifelse()` *function* rather than the `if ... else` construct. Also -- printing in the middle of an assignment statement seems a bit odd. – John Coleman Apr 05 '18 at 01:08
  • Tried doing that too. ifelse(model_data$FICO>=350 & model_data$FICO<=500 , "POOR", ifelse(model_data$FICO>=501 & model_data$FICO<=650 , "MODERATE"), "EXCELLENT") Gives an error: Error in ifelse(model_data$FICO >= 350 & model_data$FICO <= 500, "POOR", : unused argument ("EXCELLENT") –  Apr 05 '18 at 01:09
  • Try `model_data$ficocategory <- ifelse(model_data$FICO>=350 & model_data$FICO<=500,"POOR",ifelse(model_data$FICO>=501 & model_data$FICO<=650,"MODERATE","EXCELLENT"))` – John Coleman Apr 05 '18 at 01:11
  • Well this works. I get my mistake, thanks! –  Apr 05 '18 at 01:15

1 Answers1

1

There are two things going on here:

1 - The && only compares the first element of vectors. So, for instance, model_data$FICO >= 501 && model_data$FICO <= 650 is just comparing the first element of each logical vector returned by both sides of the comparison, which for your data is TRUE and TRUE (650 is >= 501 and 650 <= 650). Using & will solve this problem so that a logical vector is returned for each element-wise comparison. See this post for more information.

2 - Has already been addressed in the comments. You want to be using the vectorized ifelse function that will perform the logical comparisons and return a vector of values. In your comment above just move "EXCELLENT" inside the prior ifelse statement: ... , "MODERATE", "EXCELLENT"))

apax
  • 160
  • 7