在一个语句中创建一个带有名称的数字向量? [英] Create a numeric vector with names in one statement?
问题描述
我正在尝试将函数参数的默认值设置为命名数字.有没有办法在单个语句中创建一个?我检查了 ?numeric 和 ?vector ,但似乎并非如此.也许我可以转换/强制矩阵或 data.frame 并在一个语句中获得相同的结果?明确地说,我正在尝试一次性完成以下操作:
I'm trying to set the default value for a function parameter to a named numeric. Is there a way to create one in a single statement? I checked ?numeric and ?vector but it doesn't seem so. Perhaps I can convert/coerce a matrix or data.frame and achieve the same result in one statement? To be clear, I'm trying to do the following in one shot:
test = c( 1 , 2 )
names( test ) = c( "A" , "B" )
推荐答案
矢量元素的命名约定与列表相同:
The convention for naming vector elements is the same as with lists:
newfunc <- function(A=1, B=2) { body} # the parameters are an 'alist' with two items
如果你希望它是一个命名向量的参数(处理由 apply
提供的参数的那种函数):
If instead you wanted this to be a parameter that was a named vector (the sort of function that would handle arguments supplied by apply
):
newfunc <- function(params =c(A=1, B=2) ) { body} # a vector wtih two elements
如果你希望它是一个命名列表的参数:
If instead you wanted this to be a parameter that was a named list:
newfunc <- function(params =list(A=1, B=2) ) { body}
# a single parameter (with two elements in a list structure
这篇关于在一个语句中创建一个带有名称的数字向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!