Home > Blockchain >  how to rename complex columns with agile function that share similar items
how to rename complex columns with agile function that share similar items

Time:02-02

I have this dataset

BEZeveryextendedname <- c("A","A","A","A","B","B","B")
var <- c("B","B","B","B","B","B","B")
bar <- c("B","B","B","B","B","B","B")

Bezeveryextendedname1 <- c("A","A","A","A","B","B","B")
var1 <- c("B","B","B","B","B","B","B")
bar1 <- c("B","B","B","B","B","B","B")

dat <- data.frame(BEZeveryextendedname, var, bar, Bezeveryextendedname1, var1, bar1)

I would like to change column names that share similar elements. For example, the dataset that I would like to have would be like this:

            PrimaryA secondA thirdA         PrimaryB secondB secondB
1                    A   B   B                     A    B    B
2                    A   B   B                     A    B    B
3                    A   B   B                     A    B    B
4                    A   B   B                     A    B    B
5                    B   B   B                     B    B    B
6                    B   B   B                     B    B    B
7                    B   B   B                     B    B    B

can anyone suggest an agile way through this? Thanks

CodePudding user response:

We may do

library(data.table)
nm1 <- sub("\\d ", "", tolower(names(dat)))
i1 <- match(nm1, unique(nm1))
names(dat) <- paste0(c("Primary", "second", "third")[i1], LETTERS[rowid(i1)])

-output

> dat
  PrimaryA secondA thirdA PrimaryB secondB thirdB
1        A       B      B        A       B      B
2        A       B      B        A       B      B
3        A       B      B        A       B      B
4        A       B      B        A       B      B
5        B       B      B        B       B      B
6        B       B      B        B       B      B
7        B       B      B        B       B      B
  • Related