gpt4 book ai didi

r - 如何将变量名称的字符向量转换为在 R 中以逗号分隔的列表

转载 作者:行者123 更新时间:2023-12-01 22:35:31 26 4
gpt4 key购买 nike

我有几个数据对象(三维数组),例如object1、object2、object3。

这些对象列在一个字符向量中:

char <- c("object1","object2","object3")

然后我需要获取对象列表以用于需要其输入以逗号分隔的函数:

output <- FancyFunction(object1,object2,object3,OtherFancyStuff)

当我更改上行代码时,如何让R自动更改下行代码?我希望能够从“char”中添加或删除对象,并在“output”中相应地更改它。

我不知道该怎么做。我能做的最好的是:

output <- FancyFunction(get(char[1]),get(char[2]),get(char[3]),OtherFancyStuff)

但是如果 char 的大小改变了,这就没用了。

有什么想法吗?

最佳答案

我想这样的事情会起作用:

char <- c("object1","object2","object3")

## 2-d objects for illustration as I couldn't think of an array
## function that took arbitrary input vectors `...`
object1 <- object2 <- object3 <- array(1:25, dim = c(5,5))

do.call("rbind", mget(char))

给出

> do.call("rbind", mget(char))
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
[6,] 1 6 11 16 21
[7,] 2 7 12 17 22
[8,] 3 8 13 18 23
[9,] 4 9 14 19 24
[10,] 5 10 15 20 25
[11,] 1 6 11 16 21
[12,] 2 7 12 17 22
[13,] 3 8 13 18 23
[14,] 4 9 14 19 24
[15,] 5 10 15 20 25

要传递额外的参数,您需要稍微修改一下,将其他参数连接到 mget(char) 返回的对象上,例如:

c(mget(char), list(arg1 = "foo", arg2 = "bar", arg3 = 1:10))

> c(mget(char), list(arg1 = "foo", arg2 = "bar", arg3 = 1:10))
$object1
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25

$object2
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25

$object3
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25

$arg1
[1] "foo"

$arg2
[1] "bar"

$arg3
[1] 1 2 3 4 5 6 7 8 9 10

其中 arg1 等对应于 FancyFunction 所需的附加参数,需要根据您希望在 的定义中映射到的正式参数命名花式函数。然后调用将类似于:

OtherFancyStuff <- list(arg1 = "foo", arg2 = "bar", arg3 = 1:10)
do.call("FancyFunction", c(mget(char), OtherFancyStuff)

FancyFunction 需要 3 个参数还是第一个参数 ...?如果你能控制它,可能值得重写 FancyFunction 以将 ... 作为第一个参数并从中提取各种参数,其中任意数量的参数都可以现在提供:

FancyFunction <- function(..., other) {
dots <- list(...)
## work on components of 'dots', the length of which is number of args
## provided as ...
....
return()
}

关于r - 如何将变量名称的字符向量转换为在 R 中以逗号分隔的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24090508/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com