zhiwei li
zhiwei li

Reputation: 1711

create variable names with specific order in r

I want to get some variable names with specific order, like this

I0.n, I0.man, I0.woman, I0.low65, I0.up65

I1.n, I1.man, I1.woman, I1.low65, I1.up65

... ... ...

I99.n, I99.man, I99.woman, I99.low65, I99.up65

I tried a way but failed

num <- sprintf('%02d',0:99)
index <- c('n', 'man', 'woman', 'low65', 'up65')
vars <- paste0('I', num, '.', index)

Is there a efficent way to create the variable names with specific order?

Any help will be highly appreciated !

Upvotes: 0

Views: 71

Answers (1)

Louis
Louis

Reputation: 3632

As suggested by @MrFlick, a simple and compact way to achieve this is to use the following code:

data <- with(expand.grid(index=index, num=num), paste0('I', num, '.', index))

> data
[1] "I00.n"     "I00.man"   "I00.woman" "I00.low65" "I00.up65"  "I01.n"     "I01.man"   "I01.woman"
[9] "I01.low65" "I01.up65"  "I02.n"     "I02.man"   "I02.woman" "I02.low65" "I02.up65"  "I03.n"
...
[497] "I99.man"   "I99.woman" "I99.low65" "I99.up65" 

Hope this helps.

Upvotes: 1

Related Questions