I have a simple table in R which contains 3 columns (named 'countries_A', 'countries_B', and 'countries_C') each containing 4 countries. Now what I would like to do is write a function that searches in the table for a specific country, say "Italy", and then returns all the elements of the column where that country is in as a vector or list (with the exception of that specific country). So in my example here, as "Italy" in the column "countries_B" along with Sweden, Spain, and Switzerland, it means I would get a single vector containing all elements of column "countries_B" except Italy, meaning I would get "[Sweden, Spain, and Switzerland]" as an answer. I would really appreciate any help at all. And if possible, I would like the search to be vectorised if possible using library like dtplyr preferably. Below, I am attaching a screenshot of my table and the R script to generate that table. Many thanks in advance.
countries <- data.frame("countries_A" =
c('Belgium','Holland', 'France', 'Germany'),
"countries_B" = c('Sweden','Italy','Spain','Switzerland'),
"countries_C"= c('England','Denmark','Portugal','Hungary'))
Not too elegant:
get_vector = function(df_countries, country){
column = df_countries %>% mutate(across(everything(),
~if_else(country %in% .x, cur_column(), NULL))) %>%
mutate(var = coalesce(!!!syms(names(df_countries))))) %>%
select(var) %>% slice(1) %>% pull
vector = df_countries %>% select(column) %>% filter(.data[[column]] != country) %>% pull %>% as.vector
return(vector)
}
get_vector(df_countries = countries, 'Sweden')
> get_vector(countries, 'Sweden')
[1] "Italy" "Spain" "Switzerland"