0

Using R, I'm trying to use a for-loop to subset a larger tibble into a list of smaller ones that I can perform operations on. Below is a simplified version of one of the larger tibbles:

x <- tibble(
  species = c("nasuta","peyrieresi","parsonii","gastrotaenia","malthe","nasuta","oshaughnessyi","brevicornis","gallus","gastrotaenia","nasuta","oshaughnessyi","oshaughnessyi","brevicornis","nasuta","oshaughnessyi","sp.","brevicornis","parsonii","gallus"),
  quantity = c(1,1932,11,4,8,3,7,4,1,8,9,10,4,6,1,1,1,1,1,1),
  value = c(0,388,2750,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
)

y <- unique(x$species)
z <- list()
for (i in y) {
  z[[i]] <- subset(x, species == q[i])
}
z
             

The resulting list has contains tibbles by species with the 3 variables, but the tibbles are all empty. When I subset without the loop, for instance:

subset(x, species == q[2])
        

It returns a desired tibble. What am I doing wrong?

0 Answers0