Iterate over list lines in R

I work in R and I want to iterate over the rows of a list and refer to the column value by name:

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

Where my data look like this:

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

I know this should be trivial, but I cannot find help. Thanks in advance.

So, here is the raw data I'm working with. Example of the previous table:

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")
+5
source share
1 answer

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, suppose you want to apply a function numberTempSteps / costPerRunto each row. You would do:

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

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

+10
source

All Articles