Reputation: 4295
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")
Upvotes: 5
Views: 15424
Reputation: 78590
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
).
Upvotes: 12