我如何将以':'分隔的数字范围强制转换为该范围内的数字列表? [重复]

问题描述 投票:0回答:1

我有一个字符列表,这些字符可以是数字(例如19)或数字范围(例如20:25)。我想将此字符列表强制转换为整数,但是当我使用as.integer()强制列表转换时,范围被强制转换为NA。如何获得R以强制将格式为字符的数字范围转换为整数?

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

感谢您入住!

r dplyr coercion
1个回答
0
投票

感谢Ben,他指出了类似的问题:

unlist(lapply(unlist(strsplit(FAOCODES, ",")), function(x) eval(parse(text = x))))
© www.soinside.com 2019 - 2024. All rights reserved.