0

I have a dataframe X

  id  sales  age
   1   100    32
   2   40     27
   3   694    34
   4   500    41

I would like to create a for loop

for (i in 1:4)

{
group[i]<- X[X$id==i, ]

}

I did this trivil for loop to describe the idea, however it needs to be edited. I want to get group1 as a data frame of sales and age in which id=1, and so on for other groups. Actually I search for a solution with a for loop because I will need it later.

Thanks !

Y.esk
  • 11
  • 3

1 Answers1

1

While I think you should use split(X, X$id) as @zx8754 suggests, here's an approach using a for loop:

X <- read.table(text = "  id  sales  age
   1   100    32
   2   40     27
   3   694    34
   4   500    41", header = TRUE)

ids <- unique(X[["id"]])
grps <- vector(mode = "list", length = length(ids))
for (id in ids) {
  grps[[id]] = X[X$id == id, ]
}

grps
[[1]]
  id sales age
1  1   100  32

[[2]]
  id sales age
2  2    40  27

[[3]]
  id sales age
3  3   694  34

[[4]]
  id sales age
4  4   500  41

Or if you need the number of times in the loop, you can use:

for (i in seq_along(ids)) {
  grps[[i]] = X[X$id == ids[i], ]
}
grps

This next step is not recommended, but it would take the list and make a bunch of data.frame objects in the environment:

names(grps) <- paste0("grps", seq_len(length(grps)))
list2env(grps, .GlobalEnv)
Cole
  • 11,130
  • 1
  • 9
  • 24
  • Thanks! Do you know how to make the type of grps a data frame not a vector of lists? In this line grps <- vector(mode = "list", length = length(ids)) – Y.esk Feb 25 '20 at 11:27
  • I don't know what you want. Please edit your question to include desired output. – Cole Feb 25 '20 at 11:32
  • I want to get an output of 4 dataframes, grps1, grps2,....grps4. Instead of lists. So I have somehow to create an empty dataframe grps instead of a vector – Y.esk Feb 25 '20 at 11:39
  • See edit at the bottom. If this helps, please consider accepting the solution - next time provide a reproducible example that includes expected output. e.g., ```grp1 <- X[1, ]; grp2 <- X[2, ]; ...``` – Cole Feb 25 '20 at 11:45