Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a numeric vector with names in one statement?

Tags:

r

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" ) 
like image 987
SFun28 Avatar asked Sep 23 '11 22:09

SFun28


People also ask

How do you make a number a vector?

numerical. To convert a character vector to a numeric vector, use as. numeric(). It is important to do this before using the vector in any statistical functions, since the default behavior in R is to convert character vectors to factors.

How do you add a name to a vector file?

We can add names to vectors using two approaches. The first uses names() to assign names to each element of the vector. The second approach is to assign names when creating the vector. We can also add comments to vectors to act as a note to the user.

What is a numeric vector?

x <- c(1, 2, 3) x is a numeric vector. These are the most common kind. They are numeric objects and are treated as double precision real numbers. To explicitly create integers, add a L at the end.

How do I make a vector of the same number in R?

There are two methods to create a vector with repeated values in R but both of them have different approaches, first one is by repeating each element of the vector and the second repeats the elements by a specified number of times. Both of these methods use rep function to create the vectors.


1 Answers

The setNames() function is made for this purpose. As described in Advanced R and ?setNames:

test <- setNames(c(1, 2), c("A", "B")) 
like image 58
Aaron Schumacher Avatar answered Nov 15 '22 23:11

Aaron Schumacher