简体   繁体   English

R绑定数据帧,同时添加具有列表ID的列

[英]R bind dataframes while add column with list ID

I have a list that contains 1 to N data frames. 我有一个包含1到N个数据帧的列表。 They all have the same columns, and I need to join them all by row. 它们都具有相同的列,我需要逐行将它们加入。

The problem is, I need to add a new column to ID the portion of the new data frame related to the each original data frame. 问题是,我需要向新ID中添加一个新列,该ID与每个原始数据帧相关。

As an example: 举个例子:

$ tracks   :List of 1
  ..$ :List of 2
  .. ..$ 01-DEZ-15 11:57:34:'data.frame':   19 obs. of  5 variables:
  .. .. ..$ lon       : num [1:19] -48.6 -48.6 -48.6 -48.6 -48.6 ...
  .. .. ..$ lat       : num [1:19] -26.8 -26.8 -26.8 -26.8 -26.8 ...
  .. .. ..$ ele       : chr [1:19] "14.56" "21.77" "14.56" "15.52" ...
  .. .. ..$ time      : POSIXct[1:19], format: "2015-12-01 07:35:03" "2015-12-01 07:35:21" ...
  .. .. ..$ extensions: chr [1:19] "0" "0" "0" "0" ...
  .. ..$ NA                :'data.frame':   1899 obs. of  5 variables:
  .. .. ..$ lon       : num [1:1899] -48.6 -48.6 -48.6 -48.6 -48.6 ...
  .. .. ..$ lat       : num [1:1899] -26.8 -26.8 -26.8 -26.8 -26.8 ...
  .. .. ..$ ele       : chr [1:1899] "14.08" "13.12" "13.12" "13.12" ...
  .. .. ..$ time      : POSIXct[1:1899], format: "2015-12-01 07:39:43" "2015-12-01 07:39:53" ...
  .. .. ..$ extensions: chr [1:1899] "0" "0" "0" "0" ...

I need to merge the two lists in 1 data frame, adding the number of the list as a new column. 我需要将两个列表合并到一个数据框中,并将列表编号添加为新列。

Similar to this: 与此类似:

      Lon            Lat    Ele         Time           Ext  ID
1   -48.60467   -26.78866   14.56   2015-12-01 07:35:03 0   1
2   -48.60467   -26.78868   21.77   2015-12-01 07:35:21 0   1
3   -48.60468   -26.78869   14.56   2015-12-01 07:35:45 0   1
4   -48.60468   -26.78869   15.52   2015-12-01 07:36:09 0   2
5   -48.60468   -26.78872   13.12   2015-12-01 07:36:46 0   2

Would be possible to efficiently complete the task? 可以有效完成任务吗?

Thank you for the help. 感谢您的帮助。 Best regards. 最好的祝福。

I usually use this one liner: 我通常使用这种衬板:

tracks <- list(df1=iris, df2=iris)
Z_both <- do.call(rbind, mapply(transform, tracks, ID=seq_along(tracks), SIMPLIFY = FALSE))

mapply(transform) will add a column to each data.frame, then do.call(rbind) will stack them. mapply(transform)将为每个data.frame添加一列,然后do.call(rbind)将其堆叠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM