cbind() - 如何在一行中动态标记向量

问题描述 投票:0回答:1

考虑:

cbind("1" = 1:4)
## giving.
     1
[1,] 1
[2,] 2
[3,] 3
[4,] 4

我想要实现的目标是将“1”替换为返回字符表达式的函数,例如

cbind(as.character(1) = 1:4)

但这给出了:

Error: unexpected '=' in "cbind(as.character(1) ="

知道如何做到这一点吗?

注意:我喜欢紧凑的编码。

r cbind r-colnames
1个回答
0
投票

如果您希望能够以编程方式生成函数调用的参数名称,您可以在

setNames
上使用
list
,然后使用
do.call
将其传递给函数:

do.call('cbind', setNames(list(1:4), as.character(1)))
#>      1
#> [1,] 1
#> [2,] 2
#> [3,] 3
#> [4,] 4

或者

do.call('data.frame', setNames(list(1:4, 5:8), c('a', 'b')))
#>   a b
#> 1 1 5
#> 2 2 6
#> 3 3 7
#> 4 4 8
© www.soinside.com 2019 - 2024. All rights reserved.