Skip to content

Recycle singletons for fwrite? #4368

Closed
Closed

Description

@MichaelChirico

Saw this:

https://twitter.com/ficaryl/status/1248286097861378048

setDT(DT)[, fwrite(.SD, paste0("user", unique(userid),".csv")), by = userid, .SDcols=names(DT) ]

was struck by .SDcols=names(DT), IINM it's to force the .BY columns to be included in the output. This of course makes this unavailable on chained data.tables; the following would look relatively straightforward:

setDT(DT)[, fwrite(c(.BY, .SD), paste0("user", .BY$userid, ".csv")), by = userid]

(this works as DT[ , c(.BY, .SD), by = userid])

But fails currently because fwrite won't recycle the singletons.

The workaround is to do the recycling manually:

DT[ , by = userid, {
  out = c(.BY, .SD)
  # or for (i in seq_along(.BY)) {...}
  out[[1L]] = rep(out[[1L]], .N)
  fwrite(out, ...)
}]

Activity

  1. jangorecki commented on Apr 9, 2020

    @jangorecki
    Member

    In short, you are asking for a list method for fwrite function?

  2. MichaelChirico commented on Apr 10, 2020

    @MichaelChirico
    MemberAuthor

    fwrite already works on lists:

    data.table::fwrite(list(1:10, 10:1))
    

    what doesn't work is:

    data.table::fwrite(list(1, 1:10))
    
  3. jangorecki commented on Apr 10, 2020

    @jangorecki
    Member

    Agree that would nicely simplifies the use case from twitter, but on the other hand might introduce confusion. I would rather change unique(userid) into userid[1L] and leave it as is.

    IINM it's to force the .BY columns to be included in the output. This of course makes this unavailable on chained data.tables

    Solution proposed by you is not generic enough to address chaining gap here, it will address this case only.

    The case above c(.BY, .SD) would be addressed by #661 (if having .BY as data.table not only when i is a list).

    We either should stay as is now, incorporate your suggestion, or provide a good replacement for c to handle recycling. Which naturally should be cbind.

  4. MichaelChirico commented on Apr 10, 2020

    @MichaelChirico
    MemberAuthor

    not generic enough to address chaining gap here

    not sure I follow why, but anyway, agree cbind + .BY-as-data.table would be an equally nice solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions