Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

r - Create a numeric vector with names in one statement?

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" )
question from:https://stackoverflow.com/questions/65866866/r-how-to-merge-2-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...