naming loop value to df in while loop

hi friends ,
ı have a "while loop". it starts from 1 then goes to 20 and creates different dataframes. in this process ı want to attend loop value to red circled areas. ı do some of them ı put "i" value in code but ı don't know how can ı do others. ı need some help. thanks.

i <- 1

while (i < 20) {

OFFICE_1 <- MAIN_OFFICE |> select(c(1,2,7)) |> filter(PLACE == i)

OFFICE_1$PLACE[OFFICE_1$PLACE == i ] <- OFFICE_1$OFFICE

colnames(OFFICE_1)[3] <- "1.OFFICE"

OFFICE_1 <- OFFICE_1[ -c(1) ]

OFFICE_1 <- as.data.frame(OFFICE_1)

i = i+1

}

The code below returns 20 different data frames to the global environment (a slight modification to mtcars is used as the sample data set).

library(tidyverse)

# sample data
MAIN_OFFICE = mtcars |> 
  mutate(PLACE = 1:nrow(mtcars)) |>
  rownames_to_column('OFFICE') 

i <- 1

while (i < 20) {
  df <- MAIN_OFFICE |> select(c(1,2,7, PLACE)) |> filter(PLACE == i)
  df$PLACE[df$PLACE == i ] <- df$OFFICE
  colnames(df)[3] <- paste0(i, ".OFFICE")
  df <- df[ -c(1) ]
  df <- as.data.frame(df)
  df_name = paste0('OFFICE_', i)
  assign(df_name, df)
  i = i+1
}

# objects in environment
ls()
#>  [1] "df"          "df_name"     "i"           "MAIN_OFFICE" "OFFICE_1"   
#>  [6] "OFFICE_10"   "OFFICE_11"   "OFFICE_12"   "OFFICE_13"   "OFFICE_14"  
#> [11] "OFFICE_15"   "OFFICE_16"   "OFFICE_17"   "OFFICE_18"   "OFFICE_19"  
#> [16] "OFFICE_2"    "OFFICE_3"    "OFFICE_4"    "OFFICE_5"    "OFFICE_6"   
#> [21] "OFFICE_7"    "OFFICE_8"    "OFFICE_9"

Created on 2023-01-28 with reprex v2.0.2

Thanks so much my friend.

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.