Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through rows of list in R

Tags:

r

I am working in R and I am wanting to iterate through the rows of a list and to reference the column value by name like this:

for(row in Data) {
    name <- row$name
    age <- row$age
    #do something cool here
}

Where my data looks like this:

name, age, gender, weight
Bill, 23, m, 134
Carl, 40, m, 178

I know that this should be trivial but I can not find help on it. Thanks ahead of time.

So here is the raw data I am working with. The earlier table was an example:

structure(list(startingTemp = c(100L, 100L, 100L, 100L, 100L), 
    endingTemp = c(1L, 1L, 1L, 1L, 1L), movesPerStep = c(200000L, 
    100000L, 20000L, 10000L, 2000L), coolingCoefficient = c(0.99, 
    0.99, 0.99, 0.99, 0.99), numberTempSteps = c(459L, 459L, 
    459L, 459L, 459L), costPerRun = c(91800000L, 45900000L, 9180000L, 
    4590000L, 918000L)), .Names = c("startingTemp", "endingTemp", 
"movesPerStep", "coolingCoefficient", "numberTempSteps", "costPerRun"
), row.names = c(NA, 5L), class = "data.frame")
like image 307
Matthew Crews Avatar asked Sep 06 '12 06:09

Matthew Crews


People also ask

How do I loop through an array in R?

To iterate over items of a vector in R programming, use R For Loop. For every next iteration, we have access to next element inside the for loop block.

How do I iterate two lists at the same time in R?

To do something like this in an R-native way, you'd use the idea of a data frame. A data frame has multiple variables which can be of different types, and each row is an observation of each variable. You then access each row using matrix notation, where leaving an index blank includes everything.


1 Answers

You can do this using apply:

apply(Data, 1, function(row) {
    name <- row["name"]
    age <- row["age"]
    #do something cool here
})

This is usually used to return a new vector, matrix or list, which depends on what the function returns. For example, let's say you want to apply the function numberTempSteps / costPerRun to each row. You would do:

apply(Data, 1, function(row) row["numberTempSteps"] / row["costPerRun"])

(Note that for this example, you could also just do Data$numberTempSteps / Data$costPerRun).

like image 65
David Robinson Avatar answered Sep 29 '22 07:09

David Robinson