pabstack
pabstack

Reputation: 97

Renaming dataframes of varying number of columns in R

I would like to rename columns sequentially, for multiple dataframes with varying number of columns.

The dataframes will be put into R from a pdf that displays a table, and each pdf page is automatically assigned to a column. Automatically, the columns are named as the entire printout of the page. I simply want to replace this automatic column name with the page number.

A dataframe with 4 columns titled 1,2,3,4 or a dataframe with 5 columns titles 1,2,3,4,5 and so on.

I tried


txt_df1 <- data.frame("page1", "page2", "page3", "page4")
#remember the dataframes might have any number of columns

for (n in (1:ncol(txt_df1))){
  colnames(txt_df1[n]) <- n
}

and

txt_df1 <- data.frame("page1", "page2", "page3", "page4")
#remember the dataframes might have any number of columns

for (n in (1:ncol(txt_df1))){
  txt_df1 <- rename(txt_df1, n = n)
}

For some reason, nothing happens when either of these are run. Any suggestions on how to do this better/ make this code work?

Upvotes: 1

Views: 52

Answers (3)

KamRa
KamRa

Reputation: 349

It would be better to reference the column names in your data frames like this:

names(txt_df1)[indexNumber]

This way, you can assign names in your for-loop:

for(n in 1:ncol(txt_df1)){
  names(txt_df1)[n] <- #new name here
}

As for how to assign names, you could try this:

for(n in 1:ncol(txt_df1)){
  names(txt_df1)[n] <- paste("page_", n, sep="")
}

Upvotes: 2

whack_overflow
whack_overflow

Reputation: 110

You almost solved the issue yourself, all you need to change is moving the index [n] outside of the data.frame to colnames(txt_df1)[n] <- n

Upvotes: 2

Matt
Matt

Reputation: 7385

rename_func <- function(df) {
  df_max <- ncol(df)
  names_vec <- c(1:df_max)
  names(df) <- names_vec
  df
}

If we use the following data.frames:

txt_df1 <- data.frame("page1", "page2", "page3", "page4")
txt_df2 <- data.frame("page1", "page2")

We will get:

rename_func(txt_df1)

      1     2     3     4
1 page1 page2 page3 page4

...and

rename_func(txt_df2)

      1     2
1 page1 page2

Upvotes: 3

Related Questions