Trilobite
Trilobite

Reputation: 37

Create names for a vector of arbitrary length in R?

I want to create a function that names vectors (or rows of a matrix) of arbitrary (but known) length with two categories of variables located at arbitrary (but known) locations.

For example, if my vector is

vec <- 1:8

and I want to name the entries 1,3,5,7 as A1,A2,A3,A4 and the entries 2,4,6,8 as B1,B2,B3,B4 by providing

indexA <- c(1,3,5,7)
indexB <- c(2,4,6,8)

Since I input vectors of variable length and variable locations (both known), I need to do this automatically. The next vector might be 1:123 with a different location of the categories A and B.

Upvotes: 1

Views: 687

Answers (1)

akrun
akrun

Reputation: 886948

We use seq_along to get the sequence of the vector and paste with letters "A", "B" to give the names attribute to the vector

names(indexA) <- paste0("A", seq_along(indexA))
indexA     
# A1 A2 A3 A4 
# 1  3  5  7 

Similarly, this can be done with 'indexB'

Upvotes: 1

Related Questions