How can I create a subset a database using multiple conditions?

Viewed 63

I have a database such as this one:

enter image description here

And I need to create a smaller data frame that contains Colombia, Costa Rica, El Salvador, and Honduras (there are many other countries in the database), with the sub_region in column C empty, metro_area in column E empty, and with the data from columns L and M. Something like this:

enter image description here

I've tried the following:

COL <- subset(Basetotal, country_region == "Colombia" & sub_region_1 == "", select = c("date","transit_stations_percent_change_from_baseline"))

This with each country, but this is too slow. How can I more efficiently solve my problem with fewer lines of code?

1 Answers

Try:

library(tidyverse)

Basetotal %>% 
  filter(
    sub_region_1 == "", 
    metro_area == ""
  ) %>% 
  pivot_wider(
    id_cols = date, 
    names_from = country_region, 
    values_from = c(
      transit_stations_percent_change_from_baseline, 
      workplaces_percent_change_from_baseline
    ) # spreads data from both columns L and M
  )

You can use filter() to subset your database using multiple conditions, and pivot_wider() to spread multiple country data across the table.

Related