Home > Software design >  How to rename column of single column DataFrame in R
How to rename column of single column DataFrame in R

Time:09-28

I have a list of single column dataframes. The dataframes have all the same rows and I would like to change the value of the single column to the name of the dataframe (Index in list).

So I wrote a function:

change_colname <- function(df_list) {
  name_vector <- names(df_list)
  for (i in length(name_vector)) {
    working_name = toString(name_vector[i])
    working_df = df_list[i]
    colnames(working_df) <- working_name
  }
}

This returns:

Error in `colnames<-`(`*tmp*`, value = working_name) : 
attempt to set 'colnames' on an object with less than two dimensions

Well, then I read about single column dataframes, that they are a problem in R and thought I could transpose the dataframe.

df_list <- lapply(df_list, function(x){t(x)})
df_list <- lapply(df_list, data.frame)

Changed the function accordingly:

change_rowname <- function(df_list) {
  name_vector <- names(df_list)
  for (i in length(name_vector)) {
    working_name = toString(name_vector[i])
    working_df = df_list[i]
    rownames(working_df) <- working_name
  }
}

This returns:

Error in `rownames<-`(`*tmp*`, value = working_name) : 
attempt to set 'rownames' on an object with no dimensions

However something must be wrong in my function, since when I try in the console:

dim(df_list$df)

It returns:

[1] 96  1

and for the transposed:

[1]  1 96

Hence written in the function:

print(dim(working_df))

it returns:

NULL

but:

print(working_df)

returns the entire dataframe.

Does anybody know what is the problem here?

Thanks in advance and best regards Lukas

CodePudding user response:

How about mapply:

df_list <- list(df1 = data.frame(x = seq_len(3)), df2 = data.frame(x = seq_len(4)))
df_list_renamed <- mapply(setNames, object = df_list, nm = names(df_list), SIMPLIFY = FALSE)

In this context also see this article on drop = FALSE with data.frames.

  •  Tags:  
  • r
  • Related