4

Starting from a list of lists like outcome:

id <- c(1,2,3,4,5,1,2,3,4,5)
month <- c(3,4,2,1,5,7,3,1,8,9)
preds <- c(0.5,0.1,0.15,0.23,0.75,0.6,0.49,0.81,0.37,0.14)

l_1 <- data.frame(id, preds, month)

preds <- c(0.45,0.18,0.35,0.63,0.25,0.63,0.29,0.11,0.17,0.24)

l_2 <- data.frame(id, preds, month)

preds <- c(0.58,0.13,0.55,0.13,0.76,0.3,0.29,0.81,0.27,0.04)

l_3 <- data.frame(id, preds, month)

preds <- c(0.3,0.61,0.18,0.29,0.85,0.76,0.56,0.91,0.48,0.91)

l_4 <- data.frame(id, preds, month)

outcome <- list(l_1, l_2, l_3, l_4)

My interest is to take the assigned unique row values and create a new variable as if we do:

sample <- outcome[[1]]
sample$unique_id <- rownames(sample)

However, I don´t want to go manually because my list has 100 lists. Moreover, I don´t want to assign values manually to each row because I want to preserve the row names generated by R. How can this be done?

starball
  • 20,030
  • 7
  • 43
  • 238
vog
  • 770
  • 5
  • 11

4 Answers4

4

We may also use rownames_to_column

library(dplyr)
library(purrr)
library(tibble)
map(outcome, ~ .x %>%
    rownames_to_column('unique_id'))
akrun
  • 874,273
  • 37
  • 540
  • 662
3

With lapply and cbind:

lapply(outcome, function(x) {
  cbind(unique_id=rownames(x), x)
  })
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
3

Another base R option is to use Map

Map(function(x){
  x$unique_id <- rownames(x)
  x
}, outcome)
TarJae
  • 72,363
  • 6
  • 19
  • 66
2

Try using lapply

lapply(outcome, function(x) {
  x$unique_id <- rownames(x)
  x
  })
Park
  • 14,771
  • 6
  • 10
  • 29