rdataframelapplyr-rownamesr-colnames

Error of "incorrect number of dimensions" occurred when using lapply to a list of dataframes


I was dealing with a list of two dataframes. Both look this way.

image1

What I would like to do was to change the row names and column names so that they may look this way.

image2

Here is the code I used.

# Create a list to hold both dataframes
list_info <- c(normheart.info, disheart.info)

# Adjust the row and column names
list_info <- list_info %>% lapply(
  FUN = function(x){
    colnames(x) <- x[1,]
    rownames(x) <- x[,1]
    x <- x[-1,]
    x <- x[,-1]
  }
)

However, an error occurred as:

Error in x[1, ] : incorrect number of dimensions

I understand that the cause may be because lapply was trying looping through all the columns which have only 1 dimension. Is there a way to make it possible to have it recognize x as the dataframe itself so I can specify the first row as the column names and so too to the row names?


Solution

  • My previous answer was nonsense. I assumed things and you know how the saying goes about that.

    Your problem is in the creation of the list. c() concatenates the columns of the data.frames into one big data.frame. You need to use list(). For the future, it always helps to look at the intermediate results of your program, to spot mistakes like this.

    Where are you getting these data.frames from, anyway? If you have any control over how they're imported, most import functions allow you to define which rows and columns to use as names and which to import as data. Getting the format right from the start is almost always preferable to correcting it at some later point.