Skip to content

[[.ggproto has atypical argument names #5474

Closed

Description

@teunbrand

This is really a minor thing, but the [[.ggproto() function has name as the index argument instead of i.
This is fine for everyday use of [[-indexing, but becomes a mild annoyance when trying to programmatically extract something from a list of ggproto objects.

library(ggplot2)

# Simple function for extracting the same thing from a list of things
extract <- function(x, what) {
  lapply(x, `[[`, i = what)
}

# Works fine
x <- list(list(limits = c(NA, NA)), list(limits = c("A", "B")))
extract(x, "limits")
#> [[1]]
#> [1] NA NA
#> 
#> [[2]]
#> [1] "A" "B"

x <- list(
  scale_x_continuous(limits = c(NA, NA)), 
  scale_color_brewer(limits = c("A", "B"))
)
extract(x, "limits")
#> Error in `[[.ggproto`(X[[i]], ...): unused argument (i = "limits")

# Can fix this by changing `i` to `name`
lapply(x, `[[`, name = "limits")
#> [[1]]
#> [1] NA NA
#> 
#> [[2]]
#> [1] "A" "B"

Created on 2023-10-11 with reprex v2.0.2

Activity

  1. mjskay commented on Oct 14, 2023

    @mjskay
    Contributor

    Since the [[ primitive ignores the names of arguments and only considers position, I'd think the correct idiom in both cases would be lapply(x, `[[`, what)?

    > x = list("a")
    > `[[`(x, 1)
    [1] "a"
    > `[[`(x, i = 1)
    [1] "a"
    > `[[`(x, name = 1)
    [1] "a"
    > `[[`(i = 1, x)
    Error in 1[[x]] : invalid subscript type 'list'

    (which is not to say that the index argument name shouldn't be i)

  2. teunbrand commented on Mar 21, 2024

    @teunbrand
    CollaboratorAuthor

    Yeah you make a fair point, let's just close this.

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