【问题标题】:How to name a list of elements directly from the argument of the function using apply如何使用 apply 直接从函数的参数中命名元素列表
【发布时间】:2018-06-02 10:26:57
【问题描述】:

我有一个带有三个参数的函数,每个参数都是一个列表。这些参数的值不是固定的。它们是应用于不同数据集的另一个函数的输出。我想为每个输出传递一个名称。我的原始函数返回每个数据集的特定结果。然后,从结果中,我可以知道什么是最适合我的模型。因此,最简单的方法是使用模型名称打印所有结果。我可以手动执行此操作,但这非常耗时,有时会导致我犯错误。因此,我尝试编写一个函数来简化这项任务。

我正在考虑使用paste函数,但不知道正确的方法。

由于我的函数很长而且难度很大,所以我提供一个简单的例子。

myfun <- function(x){
    out <- list()
    out$x1 <- x^2
    out$x2 <- x^3
    out$x3 <- x^2+1
    return(out)
}

y1 <- 4
y2 <- 5
y3 <- 6


res1 <- myfun(y1)
res2 <- myfun(y2)
res3 <- myfun(y3)

myfun2 <- function(out1=list(), out2=list(), out3=list()){
    m <- length(out1)
    outfin <- lapply(1:m, function(i) c(out1[[i]], out2[[i]], out3[[i]]))
    return(outfin)
}
out1 <- list(res1$x1, res2$x1, res3$x1)
out2 <- list(res1$x2, res2$x2, res3$x2)
out3 <- list(res1$x3, res2$x3, res3$x3)

res.fin <- myfun2(out1, out2, out3)

然后我会得到这个:

> res.fin
[[1]]
[1] 16 64 17

[[2]]
[1]  25 125  26

[[3]]
[1]  36 216  37

预期输出:

我想要这样的东西:

[[1]]
[1]"x1:" 16 64 17

[[2]]
[1]"x2:" 25 125  26

[[3]]
[1] "x3:" 36 216  37

非常重要:在这个例子中,每个列表只有 3 个元素。但是,有时,我需要使用任意数量(非固定数量)的元素,例如 8 或 10。因此,我想在我的函数中使用lapply 自动为我执行此操作。

【问题讨论】:

  • 这与创建任何其他命名列表没有什么不同。当您说长度是可变的时,您是否有名称向量 c('x', 'x^2', 'x^3', ...) 或者我们从哪里获得名称?见setNames
  • 我已经解释了为什么如果不将值从数字更改为字符串就无法获得预期的输出。 “我只需要在输出中粘贴一个名称” 考虑到 R 的存储和处理方式,这并没有多大意义。为什么不在函数返回之前使用names(outfin) &lt;- paste0("x", seq_len(outfin))?
  • 等价于setNames(paste0("x", seq_len(outfin)), outfin)
  • @smci 其实是setNames(outfin, paste0("x", seq_along(outfin)))。
  • 对,@RuiBarradas ...如果你看一下setNames,它正是按照我的建议做的,所以更好:-)

标签: r list return-value named


【解决方案1】:

也许像下面这样的东西会做你想要的。

myfun2 <- function(out1=list(), out2=list(), out3=list()){
    m <- length(out1)
    outfin <- lapply(1:m, function(i) c(out1[[i]], out2[[i]], out3[[i]]))
    setNames(outfin, paste0("x", seq_along(outfin)))
}

res_list <- lapply(ls(pattern = "^res\\d+$"), get)

out1b <- unlist(lapply(res_list, `[`, 1), recursive = FALSE)
out2b <- unlist(lapply(res_list, `[`, 2), recursive = FALSE)
out3b <- unlist(lapply(res_list, `[`, 3), recursive = FALSE)

res.finb <- myfun2(out1b, out2b, out3b)

【讨论】:

  • 是的。这正是我所需要的。非常感谢。
猜你喜欢
  • 2021-10-18
  • 1970-01-01
  • 2013-12-12
  • 1970-01-01
  • 2010-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多