Home > other >  How to delete (or add) a specific string (or number) in rownames?
How to delete (or add) a specific string (or number) in rownames?

Time:06-16

For example, given a dataframe rownames:

Patient 01 On
Patient 02 PRE
Patient 03 
Patient 04 PRE

Wanted rownames:

Patient 1 On
Patient 2 PRE
Patient 3
Patient 4 PRE

Or, the other way around, that would also help.

CodePudding user response:

Starting data

           status
patient 01     On
patient 02    PRE
patient 03       
patient 04    PRE

Renaming the rownames

row.names(df) <- df %>%  
  row.names() %>%  
  str_remove_all("0") 

          status
patient 1     On
patient 2    PRE
patient 3       
patient 4    PRE

CodePudding user response:

This will not remove any 0 from 10, for example.

Starting data

dat <- data.frame(a = 1:5)

rownames(dat) <- c("Patient 01 On", "Patient 02 PRE", "Patient 03", "Patient 04 PRE", "Patient 10 PRE")

dat
#>                a
#> Patient 01 On  1
#> Patient 02 PRE 2
#> Patient 03     3
#> Patient 04 PRE 4
#> Patient 10 PRE 5

Substitution

gsub() substitutes anything that matches the pattern in its first argument with its secund argument. The arguments look a bit cryptic because they use regular expressions: in the first one, it means: 0 followed by any digit. The second one means: take the first group in brackets, i.e., the digit that's preceded by a 0.

rownames(dat) <- gsub("0(\\d)", "\\1", rownames(dat))

Output

dat
#>                a
#> Patient 1 On   1
#> Patient 2 PRE  2
#> Patient 3      3
#> Patient 4 PRE  4
#> Patient 10 PRE 5

Created on 2022-06-16 by the reprex package (v2.0.1)

  • Related