Skip to content

modify_if() can't change a list element to NULL #746

@jennybc

Description

@jennybc

I can't find a way to set certain list elements to NULL with modify_if(). Any approach I've tried either removes the elements (which seems weird, because I thought modify_*() was size-stable) or creates an extra layer of list-nesting. This may be related to some other issues around pluck-y assignment and modify, such as #636, #634.

library(purrr)

(x <- list("a", "b"))
#> [[1]]
#> [1] "a"
#> 
#> [[2]]
#> [1] "b"

(x_I_want <- list("a", NULL))
#> [[1]]
#> [1] "a"
#> 
#> [[2]]
#> NULL

modify_if(x, ~.x == "b", NULL)
#> Error: Can't convert NULL to function
#> Backtrace:
#>     █
#>  1. ├─purrr::modify_if(x, ~.x == "b", NULL)
#>  2. └─purrr:::modify_if.default(x, ~.x == "b", NULL)
#>  3.   ├─purrr::as_mapper(.f, ...)
#>  4.   └─purrr:::as_mapper.default(.f, ...)
#>  5.     └─rlang::as_function(.f)
#>  6.       └─rlang:::abort_coercion(x, friendly_type("function"))

modify_if(x, ~.x == "b", ~ NULL)
#> [[1]]
#> [1] "a"

modify_if(x, ~.x == "b", ~ list(NULL))
#> [[1]]
#> [1] "a"
#> 
#> [[2]]
#> [[2]][[1]]
#> NULL

modify_if(x, ~.x == "b", function(z) NULL)
#> [[1]]
#> [1] "a"

modify_if(x, ~.x == "b", function(z) list(NULL))
#> [[1]]
#> [1] "a"
#> 
#> [[2]]
#> [[2]][[1]]
#> NULL

Created on 2020-02-12 by the reprex package (v0.3.0.9001)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behaviormodify 🛠️

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions