Search code examples
rlistrandomsample

Randomly sampling from list values and corresponding names


What I want to do is randomly sample from the list values (in this case cities) and create a variable from that sample. Also according to the city randomly picked, another variable (country) should contain the country that corresponds to the city of that observation.

list <- list(Spain = c("Barcelona", "Madrid"), Austria = c("Vienna", "Salzburg"), 
             France = c("Paris", "Lyon"), Italy = c("Milano", "Roma"))

cbind(Country = c("Italy", "Spain"), City = c("Roma", "Madrid"))

Solution

  • A solution using data.table below. The first part makes a data table of names and countries inlcuding the whole dataset, the second samples two rows at random.

    library(data.table)
    
    dt <- lapply(list, data.frame) |> 
      rbindlist(idcol = "Country") |> 
      setnames(new=c("Country","City"))
    
    dt[sample(.N,2)]
    
       Country   City
    1: Austria Vienna
    2:   Italy Milano