Force gsub to keep trailing zeros

瘦欲@ 提交于 2020-01-14 22:43:38

问题


I want to extract the digits after "." from data.frame[ ,1] and store them in a second column as following:

1 6.354 354 
2 6.355 355
3 6.363 363
4 6.367 367
5 6.378 378
6 6.419 419
7 6.426 426
8 6.427 427
9 6.428 428
10 6.431 431
11 6.460 46
12 6.477 477
(...)

To do that I use gsub(".*\\.", "", data.frame[,1]) but this ignores the zeros as you can see e.g. in row 11. How can I extract the complete number/all digits after the "."? The column is numeric.


回答1:


If this is numeric, then we may need to convert it to character using format or sprintf, and then use sub

sub("^[^.]*[.]", "", format(v1, width = max(nchar(v1))))
#[1] "354" "355" "460" "400" "012"

data

v1 <- c(6.354, 6.355, 6.460, 6.400, 6.012)


来源:https://stackoverflow.com/questions/47593344/force-gsub-to-keep-trailing-zeros

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!