Consider this simple example:
mytib <- tibble(city_name1 = c('nyc', 'DC'),
city_name2 = c('US', 'US'),
planet_name1 = c('earth', 'moon'),
planet_name2 = c('solar', 'solar'))
# A tibble: 2 x 4
city_name1 city_name2 planet_name1 planet_name2
<chr> <chr> <chr> <chr>
1 nyc US earth solar
2 DC US moon solar
I am trying to automate the creation of a few simple variables that use tidyr. Specifically, I am simply adding the two character variables _name1 and _name2 for each topic. As below:
> mytib %>%
+ tidyr::unite(complete_city,
+ c('city_name1', 'city_name2'), remove = FALSE) %>%
+ tidyr::unite(complete_planet,
+ c('planet_name1', 'planet_name2'), remove = FALSE)
# A tibble: 2 x 6
complete_city city_name1 city_name2 complete_planet planet_name1 planet_name2
<chr> <chr> <chr> <chr> <chr> <chr>
1 nyc_US nyc US earth_solar earth solar
2 DC_US DC US moon_solar moon solar
The issue is that I would like to automate this. That is, looping over the topics city and planet. How can I do that? I tried the following with no success:
for(topic in c('city', 'planet')){
mytib <- mytib %>%
tidyr::unite('complete_{{topic}}',
c('{{topic}}_name1', '{{topic}}_name2'), remove = FALSE)
}
Thanks!