ArunK
ArunK

Reputation: 1781

unlist a list of data.tables with list index

I have a list of data.tables and I was looking to bind them together with a new column with the list index. I've currently used the rbindlist() from data.tables, But I'd like to retain the information of its list index. Can you help me do this?

set.seed(1)
x1<- data.table(x = LETTERS, y = runif(26))
x2<- data.table(x = LETTERS, y = runif(26))
l1 <- list(x1, x2)
#  head(x1)
#    x         y
# 1: A 0.2655087
# 2: B 0.3721239
# 3: C 0.5728534
# 4: D 0.9082078
# 5: E 0.2016819
# 6: F 0.8983897

#  head(x2)
#    x          y
# 1: A 0.01339033
# 2: B 0.38238796
# 3: C 0.86969085
# 4: D 0.34034900
# 5: E 0.48208012
# 6: F 0.59956583

expected result

  x         y  g
  A 0.2655087  1
  B 0.3721239  1
  C 0.5728534  1
  D 0.9082078  1
  E 0.2016819  1
  F 0.8983897  1
        .
        .
        .
  A 0.01339033 2
  B 0.38238796 2
  C 0.86969085 2
  D 0.34034900 2
  E 0.48208012 2
  F 0.59956583 2
        .
        .
        .

Upvotes: 0

Views: 1102

Answers (1)

ArunK
ArunK

Reputation: 1781

as @akrun points outs idcol is available in data.tables from v.1.9.6

rbindlist(l1, idcol = 'g')

Upvotes: 1

Related Questions