Skip to content

setnames could break out early if identical(old,new) #3783

Closed

Description

@MichaelChirico

Am writing a function that works like

if (length(idx <- grep('^_', names(x)))) setnames(x, idx, gsub('^_', '', names(x)[idx])

It would be cleaner to just write

setnames(x, gsub('^_', '', names(x)))

And (in the !length case) let setnames realize old and new are the same & return early for efficiency.

Activity

  1. MichaelChirico commented on Aug 20, 2019

    @MichaelChirico
    MemberAuthor

    Actually it already does this in the missing(new) case

    data.table/R/data.table.R

    Lines 2447 to 2451 in a8e926a

    w = which((nx != old) | (is.na(nx) & !is.na(old)))
    } else {
    w = which(nx != old)
    }
    if (!length(w)) return(invisible(x)) # no changes

    Will file a fix for !missing(new)

  2. added a commit that references this issue on Aug 20, 2019
    21a0bd5
  3. added this to the 1.12.4 milestone on Aug 23, 2019
  4. HughParsonage commented on Aug 27, 2019

    @HughParsonage
    Member

    It would be cleaner to just write

    setnames(x, gsub('^_', '', names(x)))
    

    I believe this would work already, no? If the pattern in gsub is not matched the replacement is not attempted.

  5. MichaelChirico commented on Aug 27, 2019

    @MichaelChirico
    MemberAuthor

    @HughParsonage it works but setnames still overwrites the names redundantly

  6. mattdowle commented on Aug 30, 2019

    @mattdowle
    Member

    This case is a nice one. Have been looking at it and @HughParsonage seems right to me: that case (where the pattern is not matched to any column name) does not overwrite the names redundantly. Even where only a few column names are matched, it only updates those. So if those don't touch key or index names, then the key or index name updates will be saved too. The setnames(DT, new) form seems fine then and no improvement possible.
    The PR nicely improves the other form (setnames(DT, old, new)) which wasn't doing any of the redundancy checking or saving.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions