1

The following command adds a numeric variable that indicates the rownumber to a dataframe:

some_data$.id <- as.numeric(rownames(some_data)) 

I have a list that contains many dataframes, and I want to add the variable as defined above to every dataframe in that list. I suspect I will need something like lapply for it, but I don't know how exactly. How do I do this?

Abdel
  • 5,826
  • 12
  • 56
  • 77

2 Answers2

4

You could use purrr::map with tibble::rowid_to_column

library(tidyverse)
lst <- list(mtcars, iris)
map(lst, ~rowid_to_column(.x, ".id"))
#[[1]]
#   .id  mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#1    1 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#2    2 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#3    3 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
#4    4 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#5    5 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
#...
#
#[[2]]
#    .id Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
#1     1          5.1         3.5          1.4         0.2     setosa
#2     2          4.9         3.0          1.4         0.2     setosa
#3     3          4.7         3.2          1.3         0.2     setosa
#4     4          4.6         3.1          1.5         0.2     setosa
#5     5          5.0         3.6          1.4         0.2     setosa
#...

For row names (instead of row numbers) simply replace rowid_to_column with rownames_to_column.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
1
mylist <- list(dat1=mtcars, dat2=mtcars)

mynewlist <- lapply(mylist, function(dat){
  dat$.id <- rownames(mtcars)
  dat
})

> names(mynewlist)
[1] "dat1" "dat2"
> head(mynewlist$dat1)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb               .id
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4         Mazda RX4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4     Mazda RX4 Wag
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1        Datsun 710
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1    Hornet 4 Drive
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 Hornet Sportabout
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1           Valiant
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225