Rename only specific columns in R

Viewed 146

Is there a way to rename specific columns in R data frame.

asd <- data.frame(asdds = c(1,2), sfrfr = c(3,4), dsfsg = c(4,5))
asd
  asdds sfrfr dsfsg
1     1     3     4
2     2     4     5

colnames(asd[1]) <- c(substring(names(asd[1]), 4))

I am trying to replace first columns with its substring

Expected output

asd
      ds sfrfr dsfsg
1     1     3     4
2     2     4     5
2 Answers

The syntax is :

colnames(asd)[1] <- substring(names(asd[1]), 4)
asd

#  ds sfrfr dsfsg
#1  1     3     4
#2  2     4     5

colnames(asd[1]) is a subset of dataframe, you can't rename a subset of dataframe. colnames(asd)[1] is subset of column names.

We could use rename_at

library(dplyr)
asd <-  asd %>% 
    rename_at(1,  ~ substring(., 4))
asd
#   ds sfrfr dsfsg
#1  1     3     4
#2  2     4     5
Related