Reputation:
we can use cut to create interval data further to be label, also by utilize for loop
cut function
perform_vec <- perform[["Performance"]]
perf_labs <- c(1,2,3,4,5,6)
perfcut <- cut(perform_vec,breaks = c(0,25,49.99,69.99,84.99,94.99,101),right = F, labels = perf_labs)
perfcut_df <- as.data.frame(cbind(perform_vec, perfcut))
perfcut_df$perfcut <- factor(perfcut_df$perfcut, levels = c(1,2,3,4,5,6), labels = c("D","C","B-","B","A-","A"))
resulting in the following:
i want to create it with for loop
Upvotes: 0
Views: 1080
Reputation: 269461
In solution #1 we count, in a loop, how many breaks
each input value exceeds and then use that to index into labels
. Solution #2 does the same but using outer
rather than a loop. Solution #3 uses cut
.
# input
x <- c(30, 50, 80)
breaks <- c(0,25,49.99,69.99,84.99,94.99,101)
labels <- c("D","C","B-","B","A-","A")
# solutions
# 1 - loop
lev <- 0 * x
for (b in breaks) lev <- lev + (x > b)
factor(labels[lev], levels = labels)
## [1] C B- B
## Levels: D C B- B A- A
# 2 - outer
factor(labels[rowSums(outer(x, breaks, `>`))], levels = labels)
## [1] C B- B
## Levels: D C B- B A- A
# 3 - cut
cut(x, breaks, labels)
## [1] C B- B
## Levels: D C B- B A- A
Upvotes: 2