将函数应用于以R中的特定模式开头的所有变量

use*_*292 4 r

我有与变量的R工作空间test1,test2,test3,test4,... testn.这些变量都是相同长度的列表.我想使用这些列表组合mapply(),如下例所示:

    test_matrix=mapply(c, test1, test2,..testn)
Run Code Online (Sandbox Code Playgroud)

如何做到这一点的,与开始的所有变量"test",并且这么做是为了test1,test2.. testn

flo*_*del 6

要准确回答OP要求的(mapply(c, test1, test2,..testn)),请执行以下操作:

do.call(mapply, c(FUN = c, mget(paste0("test", 1:n))))
Run Code Online (Sandbox Code Playgroud)

如果您不知道有多少(n)列表,并希望使用模式找到它们:

do.call(mapply, c(FUN = c, mget(ls(pattern = "^test\\d+$"))))
Run Code Online (Sandbox Code Playgroud)

与目前为止的其他答案一样,ls如果有超过九个对象,则使用此方法不会对对象进行正确排序,因为它们按字母顺序排序.更长但完全健壮的版本将是:

test.lists    <- ls(pattern = "^test\\d+$")
ordered.lists <- test.lists[order(as.integer(sub("test", "", test.lists)))]
do.call(mapply, c(FUN = c, mget(ordered.lists)))
Run Code Online (Sandbox Code Playgroud)