Phoebe Chair
Phoebe Chair

Reputation: 11

Rename row names from a set of dataframe

I would like to rename the rownames for this set of dataframe from:

   names                              
   <chr>                               
 1 Reporter_intensity_corrected_0___1      
 2 Reporter_intensity_corrected_0___2      
 3 Reporter_intensity_corrected_0___3 
 4 Reporter_intensity_corrected_1___1
 5 Reporter_intensity_corrected_1___2
...

to:

   names                              
   <chr>                               
 1 Reporter_intensity_corrected_0      
 2 Reporter_intensity_corrected_0      
 3 Reporter_intensity_corrected_0
 4 Reporter_intensity_corrected_1
 5 Reporter_intensity_corrected_1
...

(dropping the 3 underscores and number after it)

What can I try?

Upvotes: 0

Views: 135

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389275

In base R you can use sub to 3 underscore and a number.

df <- transform(df, names = sub('_{3}\\d+$', '', names))
df
#                           names
#1 Reporter_intensity_corrected_0
#2 Reporter_intensity_corrected_0
#3 Reporter_intensity_corrected_0
#4 Reporter_intensity_corrected_1
#5 Reporter_intensity_corrected_1

data

df <- structure(list(names = c("Reporter_intensity_corrected_0___1", 
"Reporter_intensity_corrected_0___2", "Reporter_intensity_corrected_0___3", 
"Reporter_intensity_corrected_1___1", "Reporter_intensity_corrected_1___2"
)), class = "data.frame", row.names = c("1", "2", "3", "4", "5"))

Upvotes: 1

k3b
k3b

Reputation: 354

Using regular expression in dplyr and stringr

df %>%
  mutate(names = str_remove_all(names, "(_+_+_+\\d)")

Upvotes: 1

Related Questions