Append Names to Data in List

58 Views Asked by At
set.seed(1)
d.A.100 = data.frame(x=runif(10), y = runif(10))
d.A.200 = data.frame(x=runif(10), y = runif(10))
d.B.100 = data.frame(x=runif(10), y = runif(10))
d.B.200 = data.frame(x=runif(10), y = runif(10))

mylist = list(d.A.100, d.A.200, d.B.100, d.B.200)
unlisted = do.call(rbind, mylist)

Let's say you make a list of dataframes like above and then you unlist them. I know I can just do a basic rbind but for later reasons this is how the data go. How can I add the name of the dataframe back into the unlisted dataframe so I have a new column 'dataname' equals to the name of the dataframe where those rows came from?

2

There are 2 best solutions below

0
Onyambu On

In base R. Instead of using do.call use array2DF in R >= 4.3. Note that You will need to have the names of the lists.

nms <- c('d.A.100', 'd.A.200', 'd.B.100', 'd.B.200')
d <- array2DF(array(mget(nms), length(nms), list(df_name = nms)))

data.frame(d, row.names = NULL) ## to discard the rownames

If you insist on using do.call or are stuck in older R versions, use the following code:

nms <- c('d.A.100', 'd.A.200', 'd.B.100', 'd.B.200')
do.call(rbind, Map(cbind, mylist, df_name=nms))
0
benson23 On

You can use the lst function from the tibble package to create a named list, then use that name to create a new column.

Using this method, you don't need to manually create a vector of dataframe names.

library(tibble)

mylist <- lst(d.A.100, d.A.200, d.B.100, d.B.200)
do.call(rbind, lapply(names(mylist), \(i) transform(mylist[[i]], df_name = i)))

            x          y df_name
1  0.26550866 0.20597457 d.A.100
2  0.37212390 0.17655675 d.A.100
3  0.57285336 0.68702285 d.A.100
4  0.90820779 0.38410372 d.A.100
5  0.20168193 0.76984142 d.A.100
6  0.89838968 0.49769924 d.A.100
7  0.94467527 0.71761851 d.A.100
8  0.66079779 0.99190609 d.A.100
9  0.62911404 0.38003518 d.A.100
10 0.06178627 0.77744522 d.A.100
11 0.93470523 0.48208012 d.A.200
12 0.21214252 0.59956583 d.A.200
13 0.65167377 0.49354131 d.A.200
14 0.12555510 0.18621760 d.A.200
15 0.26722067 0.82737332 d.A.200
16 0.38611409 0.66846674 d.A.200
17 0.01339033 0.79423986 d.A.200
18 0.38238796 0.10794363 d.A.200
19 0.86969085 0.72371095 d.A.200
20 0.34034900 0.41127443 d.A.200
21 0.82094629 0.47761962 d.B.100
22 0.64706019 0.86120948 d.B.100
23 0.78293276 0.43809711 d.B.100
24 0.55303631 0.24479728 d.B.100
25 0.52971958 0.07067905 d.B.100
26 0.78935623 0.09946616 d.B.100
27 0.02333120 0.31627171 d.B.100
28 0.47723007 0.51863426 d.B.100
29 0.73231374 0.66200508 d.B.100
30 0.69273156 0.40683019 d.B.100
31 0.91287592 0.33907294 d.B.200
32 0.29360337 0.83944035 d.B.200
33 0.45906573 0.34668349 d.B.200
34 0.33239467 0.33377493 d.B.200
35 0.65087047 0.47635125 d.B.200
36 0.25801678 0.89219834 d.B.200
37 0.47854525 0.86433947 d.B.200
38 0.76631067 0.38998954 d.B.200
39 0.08424691 0.77732070 d.B.200
40 0.87532133 0.96061800 d.B.200