简体   繁体   中英

How To Save Results Of A Nested Loop Separately For Each Unique Combination In R

How do I save results of my nested loop and save separately in to my lists?

My data looks likes this:

> data
  id factor
1  1      A
2  2      B
3  1      A

Then I make an empty vector of 4 lists since there are 2 unique values for id and 2 for factor

data <- data.frame("id" = c(1, 2, 1), "factor" = c("A", "B", "A"))

empty <- vector(mode = "list", length = 4)
for(i in seq_along(unique(data$id))){
  for (j in seq_along(unique(data$factor))) {
    empty[[i*j]] <- data %>%
      filter(id == unique(id)[i] & factor == unique(factor)[j])
  }
}
empty[[1]]

> empty[[1]]
  id factor
1  1      A
2  1      A

> empty[[2]]
[1] id     factor
<0 rows> (or 0-length row.names)

empty[[1]] works, but from empty[[2]] to empty[[3]] gives me an empty list. I guess I am messed up with the empty[[i*j]] part.

I would do this by using expand.grid to create a data frame with all unique combinations of your variables in data , then running a simpler for loop over a sequence representing the rows in that data frame. So:

combos <- with(data, expand.grid(id = unique(id), factor = unique(factor)))

empty <- vector(mode = "list", length = nrow(combos))

for (i in seq(nrow(combos))) {

  empty[[i]] <- filter(data, id == combos$id[i] & factor == combos$factor[i])

}

That produces this list:

> empty
[[1]]
  id factor
1  1      A
2  1      A

[[2]]
[1] id     factor
<0 rows> (or 0-length row.names)

[[3]]
[1] id     factor
<0 rows> (or 0-length row.names)

[[4]]
  id factor
1  2      B

If you want to leave the slots for the empty sets as NULL , you could put the filtering step inside an if statement.

Well, because you don't have any samples for empty[[2]] and empty[[3]] since those corresponds to 1 B and 2 A , and you should get

  id factor
1  2      B

for empty[[4]] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM