[Rd] Should subsetting named vector return named vector including named unmatched elements?

Jiří Moravec j|r|@c@mor@vec @end|ng |rom gm@||@com
Thu Jan 18 20:51:02 CET 2024


Subsetting vector (including lists) returns the same number of elements 
as the subsetting vector, including unmatched elements which are 
reported as `NA` or `NULL` (in case of lists).

Consider:

```
menu = list(
   "bacon" = "foo",
   "eggs" = "bar",
   "beans" = "baz"
   )

select = c("bacon", "eggs", "spam")

menu[select]
# $bacon
# [1] "foo"
#
# $eggs
# [1] "bar"
#
# $<NA>
# NULL

```

Wouldn't it be more logical to return named vector/list including names 
of unmatched elements when subsetting using names? After all, the 
unmatched elements are already returned. I.e., the output would look 
like this:

```

menu[select]
# $bacon
# [1] "foo"
#
# $eggs
# [1] "bar"
#
# $spam
# NULL

```

The simple fix `menu[select] |> setNames(select)` solves, but it feels 
to me like something that could be a default behaviour.

On slightly unrelated note, when I was asking if there is a better 
solution, the `menu[select]` seems to allocate more memory than 
`menu_env = list2env(menu); mget(select, envir = menu, ifnotfound = 
list(NULL)`. Or the sapply solution. Is this a benchmarking artifact?

https://stackoverflow.com/q/77828678/4868692



More information about the R-devel mailing list