Home > Blockchain >  Renaming columns based on condition about other columns (Rstudio)
Renaming columns based on condition about other columns (Rstudio)

Time:04-05

When I upload my xlsx dataset the columns like that :

enter image description here

It becomes like that in R :

enter image description here

Thus I want to replace the X... pattern with the name of the column just before and add a IR at the end

I have this for now :

data9_1 %>%
   rename_at(vars(starts_with("X")), ~ str_c(.,"IR")) 

But I don't know how to place the condition with the column before ?

thank you

CodePudding user response:

A base R approach to achieve your desired result may look like so:

data9_1 <- data.frame(
  A = 1, X18 = 2, B = 3, X19 = 4
)

to_rename <- grep("^X", names(data9_1))
names(data9_1)[to_rename] <- paste0(names(data9_1)[to_rename - 1], "IR")

data9_1
#>   A AIR B BIR
#> 1 1   2 3   4
  • Related