Iterate over rows in R

You can create list of data then rbind it into the data.frame. After it you can use subsetting. Please see the code below:

data <- list(c(a = 10, b = 100), c(a = 11,  b = 110), c(a = 12, b = 120))
df <- as.data.frame(do.call(rbind, data))
df[df$a == 10, ]$b

Output:

[1] 100

Or you can emulate Python’s approach with for loop, however not as efficient and elegant as above one:

data <- list(c(a = 10, b = 100), c(a = 11,  b = 110), c(a = 12, b = 120))
df <- as.data.frame(do.call(rbind, data))
for (index in seq.int(nrow(df)))
  if (df[index, "a"] == 10)
    print(df[index, "b"])

Output is the same:

[1] 100

Leave a Comment