SteveS
SteveS

Reputation: 4040

Add column names to expand.grid

I have 100 variables that I need to examine with all possible combinations.

Say root, SSID, kuku, pupu .....

variables <- list(root, SSID, kuku, pupu, ...)

I am using the expand.grid(variables)

But I want the column names of the expand.grid to be the same as var names.

I am aware of the set_names() function, but maybe there is an option to avoid setting the names manually.

Please advise how to do it.

Upvotes: 2

Views: 3549

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

We can store the vector as columns in data frame instead of list to avoid rewriting the names again

variables <- data.frame(root, SSID, ...)
expand.grid(variables)

With the reproducible data,

variables <- data.frame(a, b)
expand.grid(variables)

#  a b
#1 1 4
#2 2 4
#3 3 4
#4 1 5
#5 2 5
#6 3 5
#7 1 6
#8 2 6
#9 3 6

OR we can also create a named list instead

variables <- list(root = root, SSID = SSID, ...) 

and then use expand.grid

expand.grid(variables)

With the reproducible data,

variables <- list(a = a, b = b)
expand.grid(variables)

#  a b
#1 1 4
#2 2 4
#3 3 4
#4 1 5
#5 2 5
#6 3 5
#7 1 6
#8 2 6
#9 3 6

data

a <- c(1:3)
b <- c(4:6)

Upvotes: 4

Related Questions