Skip to content

first(x) # [not always the] same as x[1] #2002

Description

@Henrik-P

Because of this...

if (!length(x)) 
                return(x)

...in the code of first, the result of first(x) is not the same as x[1] when x is a zero-length vector: x vs. NA. Which is perfectly fine, but you may consider clarifying this difference in the help text.


A small example to illustrate the setting where this difference bit me. Find the first index of x == 1, within each group, where group "b" have no 1s

d <- data.table(grp = c("a", "a", "a", "b", "b", "c", "c"),
                x = c(0, 1, 1, 0, 0, 1, 1))

#    grp x
# 1:   a 0
# 2:   a 1
# 3:   a 1
# 4:   b 0
# 5:   b 0
# 6:   c 1
# 7:   c 1

# select first element using [1]
d[ , .(first.true = which(x == 1)[1]), by = grp]
#    grp first.true
# 1:   a          2
# 2:   b         NA <~~ zero-length result of grp b appears as NA
# 3:   c          1

# select first element using `first`
d[ , .(first.true = first(which(x == 1))), by = grp]
#    grp first.true
# 1:   a          2 <~~ zero-length result of grp b is "gone"
# 2:   c          1

Activity

  1. jangorecki commented on Nov 26, 2019

    @jangorecki
    Member
  2. changed the title [-]Documentation: first(x) # [not always the] same as x[1][/-] [+]first(x) # [not always the] same as x[1][/+] on Apr 6, 2020
  3. Mukulyadav2004 commented on Jun 7, 2025

    @Mukulyadav2004
    Contributor

    Hi @jangorecki @tdhock
    I'd like to propose a documentation update that addresses both this issue and #2487 as they share same principle: first() is not a synonym for x[1], but a separate, optimized function.
    My plan is to add a section - "Differences from base R subsetting" to the help page. This would clarify both the zero-length vector behavior and the stripping of attributes like names.
    Is this seems right to you, and if so can I open a PR for this?

  4. tdhock commented on Jun 8, 2025

    @tdhock
    Member

    related to a previous issue #5390 (comment)

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions