Generic code for renaming the last columns of a database

I have two databases below, the difference is in df2 I don't have the Value column. For the first database I specified colnames(df1)[-c(1, 2)] and for the second colnames(df2)[-1]. Is there a way to make this generic, that works for both database df1 and database df2, since it will always be the last two columns?

 df1<- structure(
  list(Category = c("ABC","FDE","ABC","FDE"),
       Value = c(4,1,1,2),
       x = c(5,4,3,2), y = c(5,4,0,2)),
  class = "data.frame", row.names = c(NA, -4L))

colnames(df1)[-c(1, 2)]<-c("Test1","Test2")

df2<- structure(
  list(Category = c("ABC","FDE","ABC","FDE"),
       x = c(5,4,3,2), y = c(5,4,0,2)),
  class = "data.frame", row.names = c(NA, -4L))

colnames(df2)[-1]<-c("Test1","Test2")

My first thought is to use ncol().

COLS <- ncol(df1)
colnames(df1)[c(COLS-1, COLS)]<-c("Test1","Test2")
1 Like

and my first thought to use tail.
But your solution is more simple.
And in my language: "eenvoud is het kenmerk van het ware" (Simplicity is the hallmark of the true)

df1<- structure(
  list(Category = c("ABC","FDE","ABC","FDE"),
       Value = c(4,1,1,2),
       x = c(5,4,3,2), y = c(5,4,0,2)),
  class = "data.frame", row.names = c(NA, -4L))

colnames(df1)[tail(seq_along(df1),2)] <- c("Test1","Test2")

df2<- structure(
  list(Category = c("ABC","FDE","ABC","FDE"),
       x = c(5,4,3,2), y = c(5,4,0,2)),
  class = "data.frame", row.names = c(NA, -4L))

colnames(df2)[tail(seq_along(df2),2)] <- c("Test1","Test2")
names(df1)
#> [1] "Category" "Value"    "Test1"    "Test2"
names(df2)
#> [1] "Category" "Test1"    "Test2"
Created on 2021-12-23 by the reprex package (v2.0.1)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.