Search code examples
rdplyrcoercion

How do I coerce a range of numbers separated by ':' into a list of the numbers in that range?


I have a list of characters which are either numbers (e.g. 19) or ranges of numbers (e.g 20:25). I want to coerce this list of characters into integers, but when I coerce this list using as.integer(), the ranges are coerced to NAs. How do I get R to coerce ranges of numbers formatted as characters to become integers?

FAOCODES
 [1] "15"      "27"      "56"      "44"      "79"      "79"      "83"      "68"      "71"      "75"      "89"      "92"      "94"      "97"      "101"    
[16] "103"     "108"     "116"     "122"     "137"     "125"     "135"     "136"     "149"     "176"     "191"     "195"     "197"     "201"     "181"    
[31] "187"     "203"     "205"     "210"     "211"     "236"     "242"     "249"     "254"     "267"     "270"     "292"     "289"     "260:310" "312:339"
[46] "156"     "157"     "328"     "773:821" "656"     "656"     "661"     "667"     "826"     "486"     "489"     "490:512" "567:591" "600:603" "515:560"
[61] "592"     "619"     "358:463" "161"     "216:234" "671"     "677:839"
> as.integer(FAOCODES)
 [1]  15  27  56  44  79  79  83  68  71  75  89  92  94  97 101 103 108 116 122 137 125 135 136 149 176 191 195 197 201 181 187 203 205 210 211 236 242
[38] 249 254 267 270 292 289  NA  NA 156 157 328  NA 656 656 661 667 826 486 489  NA  NA  NA  NA 592 619  NA 161  NA 671  NA
Warning message:
NAs introduced by coercion

Thanks for checking in!


Solution

  • Thanks to Ben, who pointed out a similar problem:

    unlist(lapply(unlist(strsplit(FAOCODES, ",")), function(x) eval(parse(text = x))))