简体   繁体   中英

R bind dataframes while add column with list ID

I have a list that contains 1 to N data frames. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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