2

My dataset is in a long format that has the names of countries, years and values in the columns.

I want new dataset for each country and for each year, I can do it individually but repeating that 195 is not great so I want to do it using "for"

This works for and individual country

Mali = filter(datosUnicef , CountryName == "Mali")

But this doesn't seems to work

for (i in datosUnicef$CountryName) {
   i = filter(datosUnicef , CountryName == i)
}

how can I make it work?

markus
  • 25,843
  • 5
  • 39
  • 58

1 Answers1

0

if the intention is to create multiple datasets, use group_split to split the data into list of data.frames

library(dplyr)
lst1 <- datosUnicef %>%
            group_split(CountryName)

and extract the data from list with [[ or $

NOTE: It is better not to create multiple objects in the global environment. Instead, create a list


Regarding the issue in OP's code, it is assigning to letter i in each iteration, so it gets updated. Instead, an option would be assign (not recommended though)

for(i in unique(datosUnicef$CountryName)) {
      assign(i, filter(datosUnicef, CountryName == i))
   }
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Without going into further discussion: how is this question not a dupe of [How to split a data frame?](https://stackoverflow.com/questions/3302356/how-to-split-a-data-frame) – markus Jul 25 '19 at 22:14
  • @markus I think the OP is concerned more about his `for` loop failure though `split` is an option. But, if the OP's intention is to understand the reason behind the failure of his/her code, it is not a dupe – akrun Jul 25 '19 at 22:15
  • 1
    Well, fair enough. – markus Jul 25 '19 at 22:16