Maybe this is a silly question, but what about when it is useful to access the parent environment for some row-wise operation?
For instance, lets say you have a variable v1
indicating which of the groupA, groupB, ..., groupX
variable's value you want in a new variable var
.
Is there a more convenient way of solving this problem without a lot of code?
With rowwise()
:
df <- tribble(
~groupA, ~groupB, ~v1,
"A","C","groupB",
"A","D","groupB",
"A","D","groupA"
)
df %>%
rowwise() %>%
mutate(newvar = get(v1)) %>%
ungroup()
#> # A tibble: 3 x 4
#> groupA groupB v1 newvar
#> <chr> <chr> <chr> <chr>
#> 1 A C groupB C
#> 2 A D groupB D
#> 3 A D groupA A
This doesn't work with map(?):
df %>%
mutate(newvar = map_chr(v1, get))
#> Error in mutate_impl(.data, dots) :
#> Evaluation error: object 'groupB' not found.
Though this particular problem is perhaps solvable with gather()
:
df %>%
left_join(
df %>%
gather(key, newvar, -v1) %>%
filter(key == v1) %>%
select(-key),
by = "v1")