How do I change the row names of multiple data frames in a list in R at once?

80 Views Asked by At

I have the following example list of data.frames:

df <- data.frame(A = 1:10, B = 1:10)
list1 <- list(df[1:3,],df[4:6,],df[7:10,])

[[1]]
  A B
1 1 1
2 2 2
3 3 3

[[2]]
  A B
4 4 4
5 5 5
6 6 6

[[3]]
    A  B
7   7  7
8   8  8
9   9  9
10 10 10

How do I change the row names of each data.frame (i.e., each element) of this list at the same time?

For this simple example, how would I change the row name of each row to be a sequential list of numbers starting from 1 for each data.frame in the list?

Desired output:

    [[1]]
      A B
    1 1 1
    2 2 2
    3 3 3
    
    [[2]]
      A B
    1 4 4
    2 5 5
    3 6 6
    
    [[3]]
        A  B
    1   7  7
    2   8  8
    3   9  9
    4  10 10

I can essentially accomplish creating an object with these row names :

lapply(list1,function(x){rownames(x) <- 1:dim(x)[1]})

[[1]]
[1] 1 2 3

[[2]]
[1] 1 2 3

[[3]]
[1] 1 2 3 4

But I cannot figure out how to actually apply these row names to either my previously saved object or a new object with desired row names.

3

There are 3 best solutions below

0
M-- On

We can do this by setting the rownames to 1:nrow(df) or better seq_len(nrow(df)). You almost did it with your solution. You just needed to return the dataframes in your loop instead of the rownames.

lapply(list1, function(x) {rownames(x) <- seq_len(nrow(x)); x})
#> [[1]]
#>   A B
#> 1 1 1
#> 2 2 2
#> 3 3 3
#> 
#> [[2]]
#>   A B
#> 1 4 4
#> 2 5 5
#> 3 6 6
#> 
#> [[3]]
#>    A  B
#> 1  7  7
#> 2  8  8
#> 3  9  9
#> 4 10 10
1
ThomasIsCoding On

Try `row.names<-`(..., NULL)

> lapply(list1, `row.names<-`, NULL)
[[1]]
  A B
1 1 1
2 2 2
3 3 3

[[2]]
  A B
1 4 4
2 5 5
3 6 6

[[3]]
   A  B
1  7  7
2  8  8
3  9  9
4 10 10

or

> Map(`row.names<-`, list1, list(NULL))
[[1]]
  A B
1 1 1
2 2 2
3 3 3

[[2]]
  A B
1 4 4
2 5 5
3 6 6

[[3]]
   A  B
1  7  7
2  8  8
3  9  9
4 10 10
0
Onyambu On

You could also use the row.name argument in data.frame function:

lapply(list1, data.frame, row.names = NULL)
[[1]]
  A B
1 1 1
2 2 2
3 3 3

[[2]]
  A B
1 4 4
2 5 5
3 6 6

[[3]]
   A  B
1  7  7
2  8  8
3  9  9
4 10 10