Skip to content

Instantly share code, notes, and snippets.

@leungi
Created September 11, 2018 14:31
Show Gist options
  • Save leungi/bbf89484a626afa957acc7ecffdc8b73 to your computer and use it in GitHub Desktop.
Save leungi/bbf89484a626afa957acc7ecffdc8b73 to your computer and use it in GitHub Desktop.
purrr::map2() is known to not function well with dplyr::rename(). Defining lambda in call to map2() solves the problem.https://github.com/tidyverse/purrr/issues/541
library(tidyverse)
data <- tibble::tribble(
~phase, ~fc_dt, ~oil, ~q, ~gas, ~t, ~mean,
"water", "4/1/2017", 4.602535714, 1.70775, 73.55432143, 1L, 10.60021233,
"water", "5/1/2017", 4.414064516, 5.845258065, 48.88796774, 2L, 7.86293583,
"water", "6/1/2017", 3.215866667, 4.149533333, 43.78976667, 3L, 6.47610122
)
nest_data <- data %>% nest(-phase)
nest_data
expected_output <- nest_data %>%
mutate(test = map2(data, phase, function(x, y) {
names(x) <- str_replace(names(x), "^mean$", y)
x
}))
expected_output$test
@leungi
Copy link
Author

leungi commented Sep 22, 2018

 library(tidyverse)
  data <- tibble::tribble(
    ~phase,      ~fc_dt,        ~oil,          ~q,        ~gas,  ~t,  ~mean,
    "water",  "4/1/2017", 4.602535714,     1.70775, 73.55432143,  1L, 10.60021233,
    "water",  "5/1/2017", 4.414064516, 5.845258065, 48.88796774,  2L,  7.86293583,
    "water",  "6/1/2017", 3.215866667, 4.149533333, 43.78976667,  3L,  6.47610122
  )
  
  data %>% 
    nest(-phase) -> nest_data
  
  # fails
  nest_data %>%
    mutate(test = map2(data, phase, ~ rename(.x, !!.y := mean)))
  
  # standalone works
  map2(nest_data$data, nest_data$phase, ~ rename(.x, !!.y := mean))
  
  # workaround works
  nested2 <- nest_data %>%
    mutate(test = map2(data, phase, ~ rename(.x, !!expr(phase) := mean))) %>% 
    unnest(test)

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