I'm facing an issue when I use R to recode my data.
I have a variable which is called timing_spend
, and it is a numeric variable. The data in it are continuous values. And I want to recode them into a group as the factor value.
The data sample was shown below:
timng_spend
1
34
2
45
2
8
22
10
28
62
13
16
58
49
25
69
52
71
10
21
1
....etc
The R code I am using is shown below:
group_time=function(timing_spend){
if (timing_spend >= 0 & timing_spend <= 12){
return('0-12 Month')
}else if(timing_spend > 12 & timing_spend <= 24){
return('12-24 Month')
}else if (timing_spend > 24 & timing_spend <= 48){
return('24-48 Month')
}else if (timing_spend > 48 & timing_spend <=60){
return('48-60 Month')
}else if (timing_spend > 60){
return('> 60 Month')
}}
assignment$time_group=sapply(assignment$timing_spend,group_time)
assignment$time_group=as.factor(assignment$time_group)
When I checked my data by using str
function, it shows me that "Factor w/ 5 levels "> 60 Month","0-12 Month",.." as 1, 2, 3
... etc
And it was not what I was trying to do. I want to put ">60 Month"
as "5"
, not "1"
.
Is there anyone can help me modify that? Or is this the auto mechanism of R to interpret the factor level variables? This is the plot I want to show, the tenure here was the timing i explained above, I just changed the name of it As you can see, the rank of the factor here was wired. And I want to move the "> 60 Month" to the most right side, which means it should be 5, not 1.
PS: I do not provide data sample here because I think we may not need it.