creating variables from a list

Hi, I have a list of ten countries in a tbl_df. Can I use write a for loop to use each name and create a variable and have the variable = data extracted from a data frame?

AustraliaDataCovidDeaths <- subset(deaths, Group.1 == 'Australia')
BelgiumDataCovidConfirmed <- subset(confirmed, Group.1 == 'Belgium')

Any help will be greatly appreciated

1 Like

library(tidyverse)
library(purrr)

# iris which contains  setosa     versicolor virginica in species column
walk(as.character(unique(iris$Species)),
     ~assign(envir = globalenv(),x = .,value = filter(iris,Species==.)))

setosa
versicolar
virginica
2 Likes

It's also a good practice not to create independent but related variables in the environment. Better to create a list that contains the related objects. For example:

countries <- c("Australia", "Belgium")
deaths_list <- lapply(countries, function(x) subset(deaths, Group.1 == x))

Will give you a list of the subset data frames.

You could then assign names to the list elements, e.g.

names(deaths_list) <- c("AustraliaDataCovidDeaths", "BelgiumDataCovidDeaths")

and use those reference names downstream.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

Thanks mate you are a legend, Thanks for your help last night too, much appreciated. I'll buy you a beers some time.