简体   繁体   English

如何在特定列的行中向特定 position 添加特定值?

[英]How to add a particular value to a particular position in rows of a specific column?

How to add a particular value to a particular position in rows of a specific column?如何在特定列的行中向特定 position 添加特定值? I have this column called ID:我有这个名为 ID 的列:

ID
subject01_1
subject01_2
subject01_3
...

I need to add a zero after the underline for all the subjects:我需要在所有科目的下划线后添加一个零:

ID
subject01_01
subject01_02
subject01_03
subject01_04
... 

You can use the following code to add a 0 after the _ with gsub :您可以使用以下代码在带有gsub_之后添加0

df <- read.table(text = "ID
subject01_1
subject01_2
subject01_3", header = TRUE)

df$ID <- gsub("\\_(\\d+)", "\\_0\\1", df$ID)
df
#>             ID
#> 1 subject01_01
#> 2 subject01_02
#> 3 subject01_03

Created on 2022-09-25 with reprex v2.0.2使用reprex v2.0.2创建于 2022-09-25

Using sprintf使用sprintf

library(dplyr)
library(stringr)
df1 %>%
    mutate(ID = str_replace(ID, "\\d+$",
        function(x) sprintf("%02d", as.numeric(x))))

-output -输出

   ID
1 subject01_01
2 subject01_02
3 subject01_03

data数据

df1 <- structure(list(ID = c("subject01_1", "subject01_2", "subject01_3"
)), class = "data.frame", row.names = c(NA, -3L))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM