Home > Back-end >  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?

Time:09-26

How to add a particular value to a particular position in rows of a specific column? I have this column called 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
... 

CodePudding user response:

You can use the following code to add a 0 after the _ with gsub:

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

CodePudding user response:

Using sprintf

library(dplyr)
library(stringr)
df1 %>%
    mutate(ID = str_replace(ID, "\\d $",
        function(x) sprintf("d", 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))
  • Related