Y.esk
Y.esk

Reputation: 11

Using a for loop in R

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 !

Upvotes: 0

Views: 216

Answers (1)

Cole
Cole

Reputation: 11255

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)

Upvotes: 1

Related Questions