I have a data set in R which has a column with 0-1 month, 8-9 month, etc. I want to code this column as a numeric variable with number of months. For example, instead of 8-9 month, put just 9. Thanks for help and comments.
Asked
Active
Viewed 147 times
1
-
Also check out the answers to a similar question [here](http://stackoverflow.com/questions/10431403/idiom-for-ifelse-style-recoding-for-multiple-categories) – BenBarnes Aug 22 '12 at 05:54
2 Answers
4
In one swoop
a <- c("0-1 month", "8-9 months")
as.integer(gsub("^[[:digit:]]+-([[:digit:]]+) month[s]*", "\\1", a))
-
I edited the input, because it was trying to convert "0-1" and "8-9" to integer. – GSee Aug 21 '12 at 23:09
-
If you don't have "month(s)" as part of the character string, then you can get rid of the ` month[s]*` part of the line that I give. – Charlie Aug 21 '12 at 23:12
2
With the recode
function from the car
package. It's not as succinct as the gsub
solution, but it's more flexible and it may be easier to read:
library(car)
a <- c("0-1 month", "8-9 months")
recode(a, '"0-1 month" = 1; "8-9 months" = 2')

user697473
- 2,165
- 1
- 20
- 47