1

I have the following data which looks like that:

tibble(
  name = paste0("segment",1),
  data = list(tibble(segment1 = 1:5, check = 99))
)

# A tibble: 1 x 2
  name     data            
  <chr>    <list>          
1 segment1 <tibble [5 x 2]>

I want to map over the nested data and want to use a variable (name) in dplyr. If in column name segment1 is 2 than 66 otherwise use values from column segment1

tibble(
  name = paste0("segment",1),
  data = list(tibble(segment1 = 1:5, check = 99))
) %>% 
  
  mutate(testing = map2(.x = name, .y = data, 
                        ~ .y %>% 
                            mutate(testing = ifelse((!!.x) == 2, 66, (!!.x))))) 

The unnested testing tibble should look like:

# A tibble: 5 x 3
  segment1 check testing
     <int> <dbl>   <dbl>
1        1    99       1
2        2    99      66
3        3    99       3
4        4    99       4
5        5    99       5

But I always get the error that .x couldn't be found.

Christian
  • 401
  • 1
  • 5
  • 14

1 Answers1

0

.x is already used for map2, it is better to use anonymous function to be clear which variable is referred to what.

To use string variables as column name .data pronoun should work but I am surprised it doesn't work here (or I am not using it correctly). An alternative is to use get.

library(dplyr)
library(purrr)

tibble(
  name = paste0("segment",1),
  data = list(tibble(segment1 = 1:5, check = 99))
) %>%
  mutate(testing = map2(name, data, function(p, q) {
    q %>% mutate(testing = ifelse(get(p) == 2, 66, get(p)))
  })) 

#   name     data             testing         
#  <chr>    <list>           <list>          
#1 segment1 <tibble [5 × 2]> <tibble [5 × 3]>

where data in testing column is

# A tibble: 5 x 3
#  segment1 check testing
#     <int> <dbl>   <dbl>
#1        1    99       1
#2        2    99      66
#3        3    99       3
#4        4    99       4
#5        5    99       5
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213