1

My data is:

 try<-data.frame(Gender=c("Male","Male","Female","Male","Female","Male","Female","Female","Male","Male", "Female","Male","Male","Male", "Male"), 
            Est=c(0.9956, 1.035, 2.0731, 0.0824, 3.0987, 5.0982, 6.0707, 5.0393, 2.7046, 4.0783, 0, 2.0923, 4.2348, 1.9561, 6.9262))

I need to add one more column to recode the Est value into this:

    Gender    Est    X
 1    Male 0.9956    0
 2    Male 1.0350    1
 3  Female 2.0731    2
 4    Male 0.9824    0
 5  Female 3.0987    3
 6    Male 5.0982    5
 7  Female 6.0707    6
 8  Female 5.0393    5
 9    Male 2.7046    2
 10   Male 4.0783    4
 11 Female 0.0000    0
 12   Male 2.0923    2
 13   Male 4.2348    4
 14   Male 1.9561    1
 15   Male 6.9262    6

Where (0,1]=0, (1,2]=1, (2,3]=2, (3,4]=3, (4,5]=4, (5,6]=5, (6,7]=6.

mojek
  • 195
  • 1
  • 9
  • 5
    `try$X <- floor(try$Est)` – alistaire Aug 06 '18 at 03:30
  • you can use `floor` as suggested above or use `trunc` – Onyambu Aug 06 '18 at 03:38
  • Any suggestion if I want to change the interval and try making it more dynamic? For example if I use interval (0,2]=0, (2,4]=2, (4,6]=4 or (0,3]=0, (3,6]=3 – mojek Aug 06 '18 at 03:42
  • 1
    In that case you can use my code and specify the new intervals in the breaks and labels as: `try$X = cut(x = try$Est,breaks = c(0,2,4,6),labels = c(0,2,4),right = TRUE,include.lowest = TRUE)` ` – tushaR Aug 06 '18 at 03:46
  • 1
    Either use math (`floor(try$Est / 2) * 2`) or `cut`, though be aware that the latter returns a factor which you'll want to coerce back to numeric with `as.numeric(as.character(cut(try$Est, ...)))` – alistaire Aug 06 '18 at 03:48

1 Answers1

0

cut divides the range of x into intervals and codes the values in x according to which interval they fall.

As @alistaire mentioned the output of cut is a factor. So you might want to convert it back to numeric using as.numeric(as.character(cut(try$X ....)))

try$X = cut(x = try$Est,breaks = c(0,1,2,3,4,5,6,7),labels = c(0,1,2,3,4,5,6),right = TRUE,include.lowest = TRUE)
tushaR
  • 3,083
  • 1
  • 20
  • 33
  • Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – rsjaffe Aug 06 '18 at 03:59