3

I want to categorized one variable with the next conditionals:

0 - 4: "fail" 5 - 7: "good" 8 - 10: "excellent" None of the above: NA

I tried using the recode function

The values of variable is numeric

segur <- data$segur 

Created a new variable using recode

dt1 <- recode(segur, "c(0,4)='suspenso';c(5, 7)='aceptable';c(8,10)='excelente'; else='NA'")
dt1

How can I fix?

Raq
  • 75
  • 1
  • 6

3 Answers3

0

using factor in base R

Data:

# set random seed
set.seed(1L)
# without any NA
x1 <- sample(x = 1:10, size = 20, replace=TRUE)
# with NA
x2 <- sample(x = c(1:10, NA), size = 20, replace=TRUE)

Code:

# without any NA
as.character(factor(x1, levels = c(0:10), labels = c(rep("fail", 5), rep("good", 3), rep("excellent", 3)), exclude=NA))

# with NA    
as.character(factor(x2, levels = c(0:10), labels = c(rep("fail", 5), rep("good", 3), rep("excellent", 3)), exclude=NA))
Sathish
  • 12,453
  • 3
  • 41
  • 59
0

I guess you can use cut like below

cut(segur, c(0, 4, 7, 10), labels = c("fail", "good", "excellent"))

Example

> segur
 [1]  6  1  4 -2 -1 10  8  0  5  9

> cut(segur, c(0, 4, 7, 10), labels = c("fail", "good", "excellent"))
 [1] good      fail      fail      <NA>      <NA>      excellent excellent
 [8] <NA>      good      excellent
Levels: fail good excellent
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
0

Here is a solution using the fmtr package. You can create a categorical format using the value and condition functions, and then apply the format to the numeric data using the fapply function. Here is an example:

library(fmtr)

# Create sample data
df <- read.table(header = TRUE, text = '
ID  segur
1      0
2      8
3      5
4      11
5      7')

# Create format
fmt <- value(condition(x >= 0 & x <=4, "fail"),
             condition(x >= 5 & x <=7, "good"),
             condition(x >= 8 & x <= 10, "excellent"),
             condition(TRUE, NA))

# Apply categorization
df$segur_cat <- fapply(df$segur, fmt)

# View results
df
#   ID segur segur_cat
# 1  1     0      fail
# 2  2     8 excellent
# 3  3     5      good
# 4  4    11      <NA>
# 5  5     7      good
David J. Bosak
  • 1,386
  • 12
  • 22