Separate a datraframe in subdatraframes based on a condition

Asked

Viewed 74 times

-1

I would like to generate subsets of a dataframe via loop. However, when executing this code I do not get the 5 objects.

list <- list("CO", "N", "NE", "S", "SE")


for (i in list) {
   df_name <- paste("Regiao_",i)
   df <- df_AI[df_AI$Regiao == i,]
   df[[df_name]]<- df
}

2 answers

3


The easiest way is on a line of code.

list2env(split(df_AI, df_AI$Regiao), envir = .GlobalEnv)

The split creates a list with a dataframe for each unique value of df_AI$Regiao. And list2env transforms the list elements into objects in the environment specified.

2

If I understand your question correctly, you want to create an object for each subset of the data.frame df_AI. If this is the case, you can use the function assign:

df_AI <- data.frame(Regiao = c("CO", "N", "NE", "S", "SE"),
                    numero = 1:5)

for (i in unique(df_AI$Regiao)) {
  assign(paste0("Regiao_", i), df_AI[df_AI$Regiao == i, ])
}

> objects()
[1] "df_AI"     "i"         "Regiao_CO" "Regiao_N"  "Regiao_NE" "Regiao_S" 
[7] "Regiao_SE"

> Regiao_CO
  Regiao numero
1     CO      1
  • Perfect Carlos, that was it! Thank you very much. Just an additional question. What’s the difference between paste0 and Paste (using Sep ="") ?

  • 1

    None, paste0 it’s just a shortcut.

  • Consider the response of Rui Barradas, she is more practical (among other things, by discarding the use of loop).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.