Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.data does not work properly in case data is stored in a nested column #6931

Closed
psychelzh opened this issue Sep 22, 2023 · 1 comment
Closed

Comments

@psychelzh
Copy link

psychelzh commented Sep 22, 2023

Please briefly describe your problem and what output you expect. If you have a question, please don't use this form. Instead, ask on https://stackoverflow.com/ or https://community.rstudio.com/.

Please include a minimal reproducible example (AKA a reprex). If you've never heard of a reprex before, start by reading https://www.tidyverse.org/help/#reprex.


Here my data is nested in one column called dat, then .data cannot detect a column with string, but pick() works as expect.

suppressPackageStartupMessages(library(dplyr))
library(purrr)
test <- tibble::tribble(
  ~target, ~dat,
  "x", data.frame(id = 1:5, x = 1:5)
) 
test |> 
  mutate(
    map2(
      target, dat,
      \(target, dat) {
        dat |> 
          mutate(y = .data[[target]])
      }
    )
  )
#> Error in eval(expr, envir, enclos): 找不到对象'target'
test |> 
  mutate(
    map2(
      target, dat,
      \(target, dat) {
        dat |> 
          mutate(y = pick(all_of(target)))
      }
    )
  )
#> # A tibble: 1 × 3
#>   target dat          `map2(...)` 
#>   <chr>  <list>       <list>      
#> 1 x      <df [5 × 2]> <df [5 × 3]>

Created on 2023-09-22 with reprex v2.0.2

@DavisVaughan
Copy link
Member

This is an injecting timing issue, and a known rlang limitation captured by: r-lib/rlang#845

If you wrap the anonymous function up into a separate helper, it avoids the issue

suppressPackageStartupMessages(library(dplyr))
library(purrr)

test <- tibble::tribble(
  ~target, ~dat,
  "x", data.frame(id = 1:5, x = 1:5)
) 

fn <- function(target, dat) {
  dat |> mutate(y = .data[[target]])
}

test |> 
  mutate(
    map2(target, dat, fn)
  )
#> # A tibble: 1 × 3
#>   target dat          `map2(target, dat, fn)`
#>   <chr>  <list>       <list>                 
#> 1 x      <df [5 × 2]> <df [5 × 3]>

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants