Home > Software engineering >  Assigning variable names in R from a list within expand.grid
Assigning variable names in R from a list within expand.grid

Time:05-22

I am trying to automatically generate variable names (that all follow the same naming pattern x1,x2,...) within the expand.grid function in R.

Here is a miniature version of my problem: I have a list of 25 variable names, and a matrix with 25 columns and 5 rows . Now I have to assign the names in the list to the corresponding matrix columns, but this has to be done within expand.grid (this is because my ultimate goal is to generate the grid of data, but I also need the variable names for further processing). Here is some code:

## Create list holding 25 variable names- I actually have way more than 25
ln <- vector(mode="list", length=25)
for (i in 1:25){
  
  ln[[i]]<-paste("x", i, sep="")
}
ln
ln[[1]]
## Make matrix dataset without variable/column names
sampl<- matrix(rnorm(25) , nrow = 5, ncol=25)
sampl

require(MASS)
## WHAT I WANT
## Automatically assign variable names from list ln within expand.grid
test <- expand.grid(x1=seq(min(sampl[,1]-1), max(sampl[,1] 1),
                          by=0.1),
                    x2=seq(min(sampl[,2]-1), max(sampl[,2] 1), 
                          by=0.1),
                    x3=seq(min(sampl[,3]-1), max(sampl[,3] 1),
                          by=0.1),
                     \\...and so on ...\\
                    x25=seq(min(sampl[,25]-1), max(sampl[,25] 1), 
                          by=0.1)
                   )

Alternatively, is there anyway to generate the data grid that I want from the matrix and then assign names from the list without using expand.grid?

CodePudding user response:

We can use apply to loop over the columns, get the sequence between the min and max by 0.1, set the names of the list with 'ln' values and apply expand.grid (it should be noted that the number of combinations will be huge)

test2 <- expand.grid(setNames(apply(sampl, 2, \(x) seq(min(x-1), 
       max(x   1), by = 0.1)), unlist(ln)))
  • Related