gpt4 book ai didi

r - 在 r 中添加前导 0

转载 作者:行者123 更新时间:2023-12-04 12:14:54 24 4
gpt4 key购买 nike

我有一个大型数据框,其中填充了以下字符:

 x <- c("Y188","Y204" ,"Y221","EP121_1" ,"Y233" , "Y248" ,"Y268", "BB2","BB20",  
"BB32" ,"BB044" ,"BB056" , "Y234" , "Y249" ,"Y271" ,"BB3", "BB21", "BB33",
"BB045","BB057" ,"Y236", "Y250", "Y272" , "BB4", "BB22" )

如您所见,某些标签(例如 BB20)只有两个整数。我希望整个字符列表至少有 3 个这样的整数(如果有帮助,问题只出现在 BB 标签中):

Y188, Y204, Y221, EP121_1, Y233, Y248, Y268, BB002, BB020, BB032, BB044,
BB056, Y234, Y249, Y271, BB003, BB021, BB033, BB045, BB057, Y236, Y250,
Y272, BB004, BB022

我研究了 sprintfFormatC 函数,但仍然没有成功。

最佳答案

使用嵌套 gsub 调用的有效方法:

gsub("(.*[A-Z])(\\d{1}$)", "\\100\\2",
gsub("(.*[A-Z])(\\d{2}$)", "\\10\\2", x))
# [1] "Y188" "Y204" "Y221" "EP121_1" "Y233" "Y248" "Y268" "BB002" "BB020"
# [10] "BB032" "BB044" "BB056" "Y234" "Y249" "Y271" "BB003" "BB021" "BB033"
# [19] "BB045" "BB057" "Y236" "Y250" "Y272" "BB004" "BB022"

关于r - 在 r 中添加前导 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35373210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com