r 在lapply函数中保留名称
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了r 在lapply函数中保留名称相关的知识,希望对你有一定的参考价值。
# Dummy example to generate 2 lists. One without and other with names.
# cf : https://stackoverflow.com/questions/9469504/access-and-preserve-list-names-in-lapply-function/18520422#18520422
# Get numeric columns from iris
cols <- names(which(sapply(iris, is.numeric)))
# Compute mean from each numeric column
res <- lapply(cols, function(i) {
mean(iris[,i])
})
# [[1]]
# [1] 5.843333
#
# [[2]]
# [1] 3.057333
#
# [[3]]
# [1] 3.758
#
# [[4]]
# [1] 1.199333
res <- lapply(setNames(cols,cols), function(i) {
mean(iris[,i])
})
# $Sepal.Length
# [1] 5.843333
#
# $Sepal.Width
# [1] 3.057333
#
# $Petal.Length
# [1] 3.758
#
# $Petal.Width
# [1] 1.199333
以上是关于r 在lapply函数中保留名称的主要内容,如果未能解决你的问题,请参考以下文章