热门标签 | HotTags
当前位置:  开发笔记 > 开发工具 > 正文

InsertastringbyconditioninR

如何解决《InsertastringbyconditioninR》经验,为你挑选了1个好方法。

I have this situation, but with much more information:

Barcode
NM00000512
NM000522
NM00000513
NM000514

And I would like to insert two more zeros in the shorter Barcodes, like this:

Barcode
NM00000512
NM00000522
NM00000513
NM00000514

I tried this df$Barcode <- gsub('NM000', "NM00000",df$Barcode) but didn't work. Thanks



1> Roland..:

Other answers make assumptions about the number of zeros (that there should be five). I assume that there should be exactly two characters in the front. If that's not the case, you could modify it to split the string before the first numeric digit (or according to whatever different rule applies).

barcode <- c("NM00000512", "NM000522", "NM00000513", "NM000514")


pad <- function(barcode) {
  x <- as.integer(substring(barcode, 3)) #extract numbers
  n <- max(nchar(barcode)) - 2 #desired length of number in string
  paste0(substring(barcode, 1, 2), #the two characters
         sprintf(paste0("%0", n, "i"), x) #pad with zeros
         )
}

pad(barcode)
#[1] "NM00000512" "NM00000522" "NM00000513" "NM00000514"


推荐阅读
author-avatar
大海2502902497
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有