data frame renaming

I have two questions for which I need help.

  1. How to rename the names of dataframe inside the list as their original names? like df1,df2 etc insted of numbers? I wish to have a purrr solution
  2. I need to change the column names of all the dataframes uniformly to be c("m","n","o"). I mean to say, i need to change the names by passing a vector of column names. Again I like to know the purrr solution.

Here is the MWE

Thanks and Regards,
Nithin

##Example
df_function<-function(df,col1,col2,col3,n){
df<-data.frame(col1=runif(n),col2=runif(n),col3=runif(n))
}
df1<-df_function(df1,a,b,c,5)
df2<-df_function(df2,e,f,g,5)
df3<-df_function(df3,p,q,r,5)

df_list<-list(df1,df2,df3)

For your first question, this should do what you want:

df_list <- set_names(x = df_list,
                     nm = ~ paste0("df_", seq_along(along.with = .x)))

For the 2nd question, you can do something like this:

col_names <- c("m", "n", "o")
df_list <- map(.x = df_list,
    .f = ~ set_names(x = .x,
                     nm = col_names))

Hope this helps.


Edit: Replying to post #3 by @nithinmkp

The following example changes names for 2nd and 4th columns.

col_indices <- c(2, 4)
col_names <- c("B", "D")

map(.x = df_list,
    .f = function(df)
    {
        existing_names <- names(x = df)
        existing_names[col_indices] <- col_names
        set_names(x = df,
                  nm = existing_names)
    })

Is this what you want? If it solves the question, please consider marking the thread as closed. If needed, please refer to FAQ: How do I mark a solution?.

Absolutely.. Let me ask one more question in this regard. What if I want to change only 2nd and 4th column (Assuming 4 column data frame) with a named column vector and leave the first column name unchanged?

Thanks again for the previous solution

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.