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.
We can do this by setting the
rownamesto1:nrow(df)or betterseq_len(nrow(df)). You almost did it with your solution. You just needed to return the dataframes in your loop instead of therownames.