在此示例中,我们将计算数据帧中每一列的平方偏差(在这种情况下为)mtcars。
选项A:整数索引
squared_deviance <- vector("list", length(mtcars)) for (i in seq_along(mtcars)){ squared_deviance[[i]] <- (mtcars[[i]] - mean(mtcars[[i]]))^2 }
squared_deviance 符合预期,是11元素的列表。
class(squared_deviance) length(squared_deviance)
选项B:字符索引
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 }
如果我们想要data.frame一个结果怎么办?好了,有很多选项可以将列表转换成其他对象。但是,在这种情况下,最简单的方法可能是将for结果存储在中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
尽管我们使用字符选项(B),但结果将是相同的事件。