簡體   English   中英

將多輸出 function 應用於 R 中的向量

[英]Apply multiple-output function to vector in R

我有一個 function 以列表形式返回多個輸出。 我想將此 function 應用於輸入向量,並將結果收集到向量列表中。 下面的代碼可以滿足我的要求,但有幾個缺點。 首先,我需要明確給出 f 的 output 列表的名稱“正方形”和“立方體”。 其次,我需要為每個 x 值評估 function f 兩次。 有沒有辦法在避免缺點的同時獲得與下面的代碼相同的 output ?

f <- function(x) list(square = x^2, cube = x^3)
x <- c(1, 2, 3)
desired.output <- list(
  square = sapply(X = x, FUN = function(x) f(x)$square),
  cube = sapply(X = x, FUN = function(x) f(x)$cube)
)

這應該只是在 x 上應用 function

f(x)
#$square
#[1] 1 4 9

#$cube
#[1]  1  8 27

你可以試試 function do.call這個

do.call(f, list(x))

你可以試試 -

> mapply(f, x)

    [,1] [,2] [,3]
square 1    4    9   
cube   1    8    27  

或者

> Map(f,x)

[[1]]
[[1]]$square
[1] 1

[[1]]$cube
[1] 1


[[2]]
[[2]]$square
[1] 4

[[2]]$cube
[1] 8


[[3]]
[[3]]$square
[1] 9

[[3]]$cube
[1] 27

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM