r.user.05apr
r.user.05apr

Reputation: 5456

Get name of map-loop-element when looping over tibble columns

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

Answers (1)

Ramiro Magno
Ramiro Magno

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

Related Questions