Creating Multiple New Vectors from a Dataframe

I am trying to figure out how to create new vectors conditional on levels in a dataframe. For example:

Let's say I have a dataframe with a column of sales territories labeled A through D with United States Zipcodes (postal codes) attached associated with each.
For example: the structure of my data is setup as follows:

territories <- c('A','A','A','B','B','B','C','C','C','D','D','D')
zips <-  c('60601','60602','60603','60604','85718','85719','85720','32605','32606','32607','80504','80505','80506')

df <- data.frame(territories,zips)

I would like to create separate vectors for each for the territories that contain the associated zipcodes. For example :

terr_A <- filter(df, Terr.Code == 'A')
terr_A <- terr_A[ ,"zips"]

For any one sales territory this would product a vector containing the zipcodes in that territory. I would like to repeat this for each of my territories. Perhaps via a for loop that creates the new vector with a name based on the territory, and repeats until all of the territories in the dataset have been completed.

terr_B, terr_C, terr_D etc.

Thank you!

Below is an example using a for loop as you suggest, which creates each new vector in the global environment.

territories <- c('A','A','A','A', 

zips <-  c('60601','60602','60603','60604',

df <- data.frame(territories, zips)

# function to create each vector
create_vector = function(i) {
  vector_name = paste0('terr_', i)
  vector = df$zips[df$territories == i]
  assign(vector_name, vector, envir = globalenv())

unique_territories = sort(unique(df$territories))

for(i in unique_territories) {create_vector(i)}

#> [1] "60601" "60602" "60603" "60604"
#> [1] "85718" "85719" "85720"
#> [1] "32605" "32606" "32607"
#> [1] "80504" "80505" "80506"

Created on 2022-09-23 with reprex v2.0.2.9000

Thank you! This does the job exactly. Very much appreciated

1 Like

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.