In this example we will calculate the squared deviance for each column in a data frame, in this case the mtcars
.
Option A: integer index
squared_deviance <- vector("list", length(mtcars))
for (i in seq_along(mtcars)){
squared_deviance[[i]] <- (mtcars[[i]] - mean(mtcars[[i]]))^2
}
squared_deviance
is an 11 elements list, as expected.
class(squared_deviance)
length(squared_deviance)
Option B: character index
squared_deviance <- vector("list", length(mtcars))
Squared_deviance <- setNames(squared_deviance, names(mtcars))
for (k in names(mtcars)){
squared_deviance[[k]] <- (mtcars[[k]] - mean(mtcars[[k]]))^2
}
What if we want a data.frame
as a result? Well, there are many options for transforming a list into other objects. However, and maybe the simplest in this case, will be to store the for
results in a data.frame
.
squared_deviance <- mtcars #copy the original
squared_deviance[TRUE]<-NA #replace with NA or do squared_deviance[,]<-NA
for (i in seq_along(mtcars)){
squared_deviance[[i]] <- (mtcars[[i]] - mean(mtcars[[i]]))^2
}
dim(squared_deviance)
[1] 32 11
The result will be the same event though we use the character option (B).