subset using loop in r in r

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.r
# create a vector of numbers
x <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# initialize an empty list to store the subsets
subsets <- list()

# loop through each element in the vector
for (i in 1:length(x)) {
  # check if the element is even
  if (x[i] %% 2 == 0) {
    # if it is, append it to the "subsets" list
    subsets[[length(subsets) + 1]] <- x[i]
  }
}

# show the subsets
subsets
384 chars
18 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