将 R 中的 apply 函数用于特定的函数值
Using apply function in R to a particular function value
所以我有一个具有多个 return 值的函数。这方面的一个例子如下:
Test.function <- function(x){
a <- x^2
b <- x^3
c <- x^4
return(list(
"a" = a,
"b" = b,
"c" = c
))
}
现在,我想使用 'apply' 函数只提取其中一个值。例如 'b'。以下代码生成一个包含 10 个对象的列表,每个对象都有一个包含 a、b 和 c 的向量。我想创建一个只有 b 的矩阵。
apply(matrix(rnorm(200),nrow = 20), 2, FUN= Test.function)
使用 lapply
或 sapply
您可以从名为 "b"
的列表中提取元素
set.seed(100)
fulloutput <- apply(matrix(rnorm(200),nrow = 20), 2, FUN= Test.function)
lapply(fulloutput, "[[", "b")
或一行:
sapply(apply(matrix(rnorm(200),nrow = 20), 2, FUN= Test.function), "[[", "b")
所以我有一个具有多个 return 值的函数。这方面的一个例子如下:
Test.function <- function(x){
a <- x^2
b <- x^3
c <- x^4
return(list(
"a" = a,
"b" = b,
"c" = c
))
}
现在,我想使用 'apply' 函数只提取其中一个值。例如 'b'。以下代码生成一个包含 10 个对象的列表,每个对象都有一个包含 a、b 和 c 的向量。我想创建一个只有 b 的矩阵。
apply(matrix(rnorm(200),nrow = 20), 2, FUN= Test.function)
使用 lapply
或 sapply
您可以从名为 "b"
set.seed(100)
fulloutput <- apply(matrix(rnorm(200),nrow = 20), 2, FUN= Test.function)
lapply(fulloutput, "[[", "b")
或一行:
sapply(apply(matrix(rnorm(200),nrow = 20), 2, FUN= Test.function), "[[", "b")