Suppose we have a vector x
and we want to subset it based on a certain condition using a loop. Here's an example code that demonstrates this:
main.r384 chars18 lines
In this example, we create a vector
of numbers from 1 to 10, and then we create an empty list
called subsets
to store the subsets we'll be creating.
Next, we use a for
loop to iterate over each element in x
. In each iteration we check whether that element is even by using the modulo operator (%%
). If the element is even, we append it to the subsets
list using the index length(subsets) + 1
(i.e., the next available index in the list).
Finally, we show the resulting subsets by printing the subsets
list. Note that we can also access each subset individually using its index (e.g., subsets[[1]]
for the first subset).
gistlibby LogSnag