R to generate a unique identifier with a prefix?

I have a table called "pipel" that contains more than 10,000 rows. I would like to add an identifier column to assign a unique identifier for each row. The unique identifier must be 30 digits long and starts with "AKM_CC_Test_". I used the code below as a starting point, but not sure how to format it to add a prefix and make it 30 digits long.

id <- rownames(pipel)
pipel <- cbind(id=id, pipel)

For example, the identifier of the first line should look like this: AKM_CC_Test_000000000000000001

+4
source share
2 answers

sprintf(). 30- , "AKM_CC_Test_" 1:nrow(pipel) .

x <- "AKM_CC_Test_"
sprintf("%s%0*d", x, 30 - nchar(x), 1:nrow(pipel))
  • %s x
  • %0*d 1:nrow(pipel) * x. * 30 - nchar(x) ( , 18, )

5 (1:5)

x <- "AKM_CC_Test_"
sprintf("%s%0*d", x, 30 - nchar(x), 1:5)
# [1] "AKM_CC_Test_000000000000000001" "AKM_CC_Test_000000000000000002"
# [3] "AKM_CC_Test_000000000000000003" "AKM_CC_Test_000000000000000004"
# [5] "AKM_CC_Test_000000000000000005"
+7

: seq , paste paste0. 0.

:

  • stri_pad stringi ( )
  • str_pad stringr ( )
  • sprintf ( )
  • formatC (, C printf)

, , , . options with_options devtools.

, . .

formatC:

uid <- paste0("AKM_CC_Test_", formatC(1:10000, width = 18, format = "d", flag = "0"))
head(uid)
[1] "AKM_CC_Test_000000000000000001" "AKM_CC_Test_000000000000000002" "AKM_CC_Test_000000000000000003" "AKM_CC_Test_000000000000000004"
[5] "AKM_CC_Test_000000000000000005" "AKM_CC_Test_000000000000000006"

stringr:

uid <- paste0("AKM_CC_Test_", str_pad(1:10000, 18, pad = "0")) # remember to load stringr
head(uid)
[1] "AKM_CC_Test_000000000000000001" "AKM_CC_Test_000000000000000002" "AKM_CC_Test_000000000000000003" "AKM_CC_Test_000000000000000004"
[5] "AKM_CC_Test_000000000000000005" "AKM_CC_Test_000000000000000006"

sprintf:

head(sprintf("%s%0*d", "AKM_CC_Test_", 18,  1:10000))
[1] "AKM_CC_Test_000000000000000001" "AKM_CC_Test_000000000000000002" "AKM_CC_Test_000000000000000003" "AKM_CC_Test_000000000000000004"
[5] "AKM_CC_Test_000000000000000005" "AKM_CC_Test_000000000000000006"

stri_pad stringi:

uid <- paste0("AKM_CC_Test_", stri_pad(1:10000, 18, pad = "0")) # remember to load stringi
head(uid)
[1] "AKM_CC_Test_000000000000000001" "AKM_CC_Test_000000000000000002" "AKM_CC_Test_000000000000000003" "AKM_CC_Test_000000000000000004"
[5] "AKM_CC_Test_000000000000000005" "AKM_CC_Test_000000000000000006"
-2

Source: https://habr.com/ru/post/1657222/


All Articles