0

I have a list of 2 or more data sets, each with the same columns except for their first column. For example:

df1 <- data.frame(df1 = c("A","B"), col1 = c(0,0), col2 = c(0,0))
 source col1 col2
1   A    0    0
2   B    0    0


> df2 <- data.frame(df2 = c("C","D"), col1 = c(0,0), col2 = c(0,0))
 index col1 col2
1   C    0    0
2   D    0    0

What would be the best way to achieve the following objectives? - Combine them in the following format:

    df  value  col1 col2
source   A    0    0
source   B    0    0
 index   C    0    0
 index   D    0    0

- Combine 3 or more datasets in the same manner

I think a function would be best where the input can be a list of datasets and I can use rbindlist or something. However, I am stuck at joining and transforming the first column.

southwind
  • 636
  • 4
  • 15
  • 2
    You can pass a named list to `rbindlist` - `rbindlist(mget(c("df1","df2")), idcol="id")` - just hunting for a duplicate. – thelatemail Sep 03 '18 at 00:55
  • I dont think my question is a duplicated of the other one. I have amended the data frame so it will be clearer. The first id column should take the column name of the first column in each dataset – southwind Sep 04 '18 at 00:40
  • not an exact dupe but its similar enough for you to start from there. you can try this: `rbindlist( lapply(mget(c("df1","df2")), function(x) data.table(df=names(x)[1L], value=x[,1L], x[-1L] )) )` – chinsoon12 Sep 05 '18 at 03:44

0 Answers0