Reputation: 5456
I would like to extract the column name of the current column when looping with map. For example, I would like to un-do the scaling if some variables:
library(tidyverse)
d <- tibble(a = runif(10), b = runif(10), c = runif(10))
l <- list(a = list(min = -19, max = 20), b = list(min = 22, max = 55), c = list(min = 80, max = 120))
restore <- function(x, r) x * (r$max - r$min) + r$min
my_cols <- c("a", "c")
d %>%
select(!!!my_cols) %>%
map(~restore(.x, l[[name(.x)]]))
# Error in name(.x) : could not find function "name"
How can I fix this?
Upvotes: 4
Views: 470
Reputation: 3175
Easy with imap
from purrr
.
Note that when using the formula shortcut, the first argument is the value (.x
), and the second is the position/name (.y
).
See the help page on imap
for more details. But essentially if the object you are iterating over has names, then the second argument (.y
) to the function is the name (otherwise it's the position).
library(tibble)
library(purrr)
library(dplyr)
d <- tibble(a = runif(10), b = runif(10), c = runif(10))
l <- list(a = list(min = -19, max = 20), b = list(min = 22, max = 55), c = list(min = 80, max = 120))
restore <- function(x, r) x * (r$max - r$min) + r$min
my_cols <- c("a", "c")
d %>%
select(!!!my_cols) %>%
imap(~restore(.x, l[[.y]]))
Upvotes: 6