Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing column names using regular expressions

Tags:

r

I have five columns named organoleptic.1., organoleptic.2., organoleptic.3. and so forth in a data frame called "df". I want to rename them to organoleptic1, organoleptic2, organoleptic3, etc. That is, I want to remove the two dots surrounding the number. I did it using the names function:

names(df)[names(df) == "organoleptic.1."] <- "organoleptic1"
names(df)[names(df) == "organoleptic.2."] <- "organoleptic2"
names(df)[names(df) == "organoleptic.3."] <- "organoleptic3"
names(df)[names(df) == "organoleptic.4."] <- "organoleptic4"
names(df)[names(df) == "organoleptic.5."] <- "organoleptic5"

However, I would like to do it just typing one line of code. Is it possible to do that using regular expressions or any other trick? Many thx!

like image 851
Antonio Serrano Avatar asked Oct 23 '25 17:10

Antonio Serrano


1 Answers

We can try by using gsub function. Edit: Fixed from sub to gsub

colnames(df) <- gsub('.', '', colnames(df), fixed=TRUE)
like image 198
mtoto Avatar answered Oct 26 '25 07:10

mtoto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!