I am trying to create a data frame using the expand.grid to find all possible combinations of two variables with numeric values and two vectors. However, I don't want the vectors to be split into their individual elements during the combination process.
I first tried to assign names to the vectors outside the data frame set up and then just use the names in the combination command. However, this prevents me from extracting the vectors' values from the data frame as R now recognizes it as just a factor.
The following is a simplified version of the code I'm using:
datamatrix <- matrix( c(1:36), nrow = 6, byrow = TRUE)
vector1 <- c(1, 2, 3)
vector2 <- c(4, 5, 6)
sample_table <- expand.grid(variable1 <- c("a", "b", "c"),
variable2 <- c("d", "e", "f"),
vector <- c(vector1, vector2))
This produces a third column of single values of the elements of vector1 and vector 2 (1,2,3,4,5,6) as opposed to the vectors themselves.
My goal is the following (the ## indicating desired output):
sample_table[1,3]
## vector1
Then I want to be able to use this as an actual vector, not as a factor:
datamatrix[sample_table[1,3],]
## [,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 2 3 4 5 6
[2,] 7 8 9 10 11 12
[3,] 13 14 15 16 17 18
I also tried creating a tibble version of the data frame with the crossing() command in place of expand.grid. However, this still splits my vectors up into individual elements rather than keeping the whole vector.
Is there some kind of command or operator I can use to prevent R from splitting up my vector inside a combination command?