This is the ideal case for the function split
. With the function split
you can share your data.frame
according to the values in the column Quantidade
:
tab_split <- split(tab, tab$Quantidade)
The result in the above command was saved in a list of the four data.frames
separated:
str(tab_split)
List of 4
$ 1:'data.frame': 20 obs. of 2 variables:
..$ Nome : Factor w/ 26 levels "A","B","C","D",..: 22 2 12 5 25 22 24 15 20 19 ...
..$ Quantidade: num [1:20] 1 1 1 1 1 1 1 1 1 1 ...
$ 2:'data.frame': 25 obs. of 2 variables:
..$ Nome : Factor w/ 26 levels "A","B","C","D",..: 26 10 20 17 20 21 1 1 14 20 ...
..$ Quantidade: num [1:25] 2 2 2 2 2 2 2 2 2 2 ...
$ 3:'data.frame': 30 obs. of 2 variables:
..$ Nome : Factor w/ 26 levels "A","B","C","D",..: 24 21 1 19 24 13 6 22 25 15 ...
..$ Quantidade: num [1:30] 3 3 3 3 3 3 3 3 3 3 ...
$ 4:'data.frame': 25 obs. of 2 variables:
..$ Nome : Factor w/ 26 levels "A","B","C","D",..: 8 22 25 3 5 21 23 12 5 8 ...
..$ Quantidade: num [1:25] 4 4 4 4 4 4 4 4 4 4 ...
I recommend leaving the four data.frames on the list, it’s easier and more organized to work with. But if you want to put data.frames in the global environment just use list2env()
:
names(tab_split) <- paste0("df", seq_along(tab_split))
list2env(tab_split, envir = globalenv())
It was not clear to me what the "save to different directories" in the question title means. The body of the question makes no reference to saving the created data frames.
– Marcus Nunes