Issue
This Content is from Stack Overflow. Question asked by John M.
I’m dealing with a quite complicated data frame. I’m trying to rename its columns by adding some terminal digits to each column several times. How can I do that?
Let me make an example:
df=data.frame(disease=c("HB1","HB2","HB3","HB4"),
region="AZ",
hospitalAZ=runif(4),
hospitalAZ=runif(4),
hospitalAZ=runif(4),
hospitalAZ=runif(4))
This is just a stupid example. The outcome should be: the columns after “region” should be named HospitalAZ1, HospitalAZ2, HospitalAZ1, HospitalAZ2. I looking for a parsimonious way of adding, in this case, 1 and 2 to the 4 columns with repetition (2 times in this case). Then, how can I extract the outcome in an xls file?
Solution
We could use rename_with
library(dplyr)
library(stringr)
df <- df %>%
rename_with(~ make.unique(str_c("HospitalAZ", rep(1:2,
length.out = length(.x)))), starts_with("hospitalAZ"))
-output
disease region HospitalAZ1 HospitalAZ2 HospitalAZ1.1 HospitalAZ2.1
1 HB1 AZ 0.1796734 0.28729264 0.8549300 0.8486733
2 HB2 AZ 0.8518319 0.03438504 0.5909983 0.8378173
3 HB3 AZ 0.3961885 0.67294967 0.4627137 0.5484321
4 HB4 AZ 0.9955195 0.38767387 0.1961428 0.6010028
NOTE: matrix
can have duplicate column names, but data.frame
duplicate column names are not recommended and in tidyverse the duplicates can result in error
In base R
, we may do
i1 <- startsWith(names(df), "hospitalAZ")
names(df)[i1] <- paste0("HospitalAZ", rep(1:2, length.out = sum(i1)))
> df
disease region HospitalAZ1 HospitalAZ2 HospitalAZ1 HospitalAZ2
1 HB1 AZ 0.1796734 0.28729264 0.8549300 0.8486733
2 HB2 AZ 0.8518319 0.03438504 0.5909983 0.8378173
3 HB3 AZ 0.3961885 0.67294967 0.4627137 0.5484321
4 HB4 AZ 0.9955195 0.38767387 0.1961428 0.6010028
This Question was asked in StackOverflow by John M. and Answered by akrun It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.