0

For example say I have some data frame, DF.

DF has a column called "Target" and it consists of factor variable target names such as "A", "B", "C" , etc. For simplification just assume it has only those three.

I want to define three new data frames,

for example if I did

for(i in levels(DF$Target)){
Dat.i=Dat%>%
filter(Target==i)
}

It would run three times but the final result would still be a single data frame, Dat.i , with target=C.

I want there to be three new data frames literally called Dat.A, Dat.B and Dat.C, each corresponding to the the specific target. not Dat.i.

How can this be done?

Quality
  • 113
  • 6

1 Answers1

1

Not exactly what you want, but I think the best way to do this is to use a list

Dat <- list()
for(i in levels(DF$Target)){
  Dat[[i]] <- Dat%>%
           filter(Target==i)
}

Then you can access to your dataframes by doing Dat[["A"]],Dat[["B"]]...

If really you want to create different objects called Dat.A, Dat.B etc you can do this using

Dat <- list()
for(i in levels(DF$Target)){
  assign(paste0('Dat.',i), Dat%>%
                                filter(Target==i))
}
fmarm
  • 4,209
  • 1
  • 17
  • 29