SmOg3R
SmOg3R

Reputation: 294

R - create vector of names containing range of numbers

I have a list of variable names {'X14_question_1', 'X14_question_2' ... etc }, let's say there are 20 of them. How do I assign those names to a vector without needing to type in all of them by hand?

Can I do it somehow similarly to this - vector = c('X14_question_'1':20) (this exact syntax isn't working obv), or do I must use the loop?

Upvotes: 0

Views: 648

Answers (3)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

I like sprintf for these types of things since it also allows you to do some transformation in the process.

Here's a basic (no transformation) approach:

vec1 <- sprintf('X14_question_%d', 1:20)
head(vec1)
# [1] "X14_question_1" "X14_question_2" "X14_question_3" "X14_question_4"
# [5] "X14_question_5" "X14_question_6"

Here's an approach that pads zeroes in the number to make sorting easier.

vec2 <- sprintf('X14_question_%02d', 1:20)
head(vec2)
# [1] "X14_question_01" "X14_question_02" "X14_question_03" "X14_question_04"
# [5] "X14_question_05" "X14_question_06"

Upvotes: 1

Barranka
Barranka

Reputation: 21067

Let's see if this helps you:

vars <- paste('X14_question_', 1:20)
v <- vector()
for(i in 1:length(vars)) {
  v[i] <- eval(parse(text = vars[i]))
}

Maybe this is not the cleanest way, but it may work

Upvotes: 0

SmOg3R
SmOg3R

Reputation: 294

Turns out it was relatively easy to find an answer, I just wasn't looking in the right place!

Thanks anyway. :)

vector=c(paste("X14_question_",1:20,sep=""))

Upvotes: 4

Related Questions