R 如何在数据帧中添加前导零

R 如何在数据帧中添加前导零,r,R,我正在尝试更改数据的格式。我有一个从1到15的中心号码和一个从1到3000的参与者号码 我希望他们以零开始,这样中心号码将有两位数字,参与者号码将有4位数字。(例如,参与者编号1将为0001) 谢谢大家! 您可以使用“stringr”软件包中的stru pad功能 library(stringr) values <- c(1, 5, 23, 123, 43, 7) str_pad(values, 3, pad='0') 在您的情况下,由于字符串有两个部分,您可以应用这样的函数来正确填充字

我正在尝试更改数据的格式。我有一个从1到15的中心号码和一个从1到3000的参与者号码 我希望他们以零开始,这样中心号码将有两位数字,参与者号码将有4位数字。(例如,参与者编号1将为0001)


谢谢大家!

您可以使用“stringr”软件包中的
stru pad
功能

library(stringr)
values <- c(1, 5, 23, 123, 43, 7)
str_pad(values, 3, pad='0')
在您的情况下,由于字符串有两个部分,您可以应用这样的函数来正确填充字符串

# dummy data
centre_participants <- c('1-347', '13-567', '9-7', '15-2507')

# split the strings on "-"
centre_participants <- strsplit(centre_participants, '-')

# apply the right string padding to each component and join together
centre_participants <- sapply(centre_participants, function(x) 
  paste0(str_pad(x[1], 2, pad='0'),'-',str_pad(x[2], 4, pad='0')))

查看
stringr::str_pad
。请参阅中的详细讨论,谢谢您的回答!代码运行良好,但我无法将其恢复到数据帧中。我需要它将data.frame与另一个合并,其中我有xx xxxx(中心参与者)格式的数据。但一旦我使用str_pad命令,我就无法再将中心与参与者信息结合起来。因为我没有两个列表都包含的信息,所以我没有任何可以合并的变量。是否有保留data.frame并只更改一列中的数字的选项?啊,我明白你的意思,我将编辑我的答案。这更好地回答了你的问题吗?是的,非常感谢!
# dummy data
centre_participants <- c('1-347', '13-567', '9-7', '15-2507')

# split the strings on "-"
centre_participants <- strsplit(centre_participants, '-')

# apply the right string padding to each component and join together
centre_participants <- sapply(centre_participants, function(x) 
  paste0(str_pad(x[1], 2, pad='0'),'-',str_pad(x[2], 4, pad='0')))
[1] "01-0347" "13-0567" "09-0007" "15-2507"