0

Maybe i dont have to use cut but i can not find any other method What i am trying to do is, on this table

y2018<- matrix(c(7.8,5,9,4,2.3,4,6),ncol=1,byrow=TRUE)
colnames(y2018) <- c("Numb")

i want to add a column so it will be like this

y2018$d_grade <- cut(y2018$Numb, c(-Inf,4.9,6.25,7.5,8.75,10), labels = c('Failed', 'Medium', 'Good', 'Very Good', 'Excellent'))

but I want to write failed where lower than 5 and then automatically cut the rest numbers, i dont want to write c(-Inf,4.9,6.25,7.5,8.75,10) i dont know if its possible

something like this

y2018$d_grade <- cut(y2018$Numb, 5, labels = c('Failed', 'Medium', 'Good', 'Very Good', 'Excellent'))

Thanks Anyways

Abyss
  • 5
  • 2
  • please add your data and desired results into the question as "copy&paste" code (not linked images). Have a read of this excellent guidance: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – dww May 25 '21 at 14:20

1 Answers1

0
  • Firstly, you have to understand the nature of matrix, that must contain all value with same types.
  • Therefore, you should start your data as dataframe or tibble
y2018<- as.data.frame(matrix(c(7.8,5,9,4,2.3,4,6),ncol=1,byrow=TRUE))
colnames(y2018) <- c("Numb")

  Numb
1  7.8
2  5.0
3  9.0
4  4.0
5  2.3
6  4.0
7  6.0

Then, if you want to add data, use cbind or dplyr mutate

d_grade <- cut(y2018$Numb, c(-Inf,4.9,6.25,7.5,8.75,10), 
                  labels = c('Failed', 'Medium', 'Good', 'Very Good', 'Excellent'))
cbind(y2018, d_grade)

  Numb   d_grade
1  7.8 Very Good
2  5.0    Medium
3  9.0 Excellent
4  4.0    Failed
5  2.3    Failed
6  4.0    Failed
7  6.0    Medium

There are other way than using cut such as dplyr mutate + case_when check the documentation further.

Pete Kittinun
  • 593
  • 3
  • 15