version: 2015-07-07 17:30:35 Europe/Berlin
Let’s say we have two character vectors: authors and books.
authors <- c("William Shakespeare", "Ernest Hemingway", "Thomas Mann")
authors
## [1] "William Shakespeare" "Ernest Hemingway" "Thomas Mann"
books <- c("Hamlet", "The Old Man and the Sea", "Reflections of an Unpolitical Man")
books
## [1] "Hamlet" "The Old Man and the Sea"
## [3] "Reflections of an Unpolitical Man"
We can create all combinations by using the function expand.grid:
x <- expand.grid(authors, books, stringsAsFactors = FALSE)
This returns a data frame:
x
## Var1 Var2
## 1 William Shakespeare Hamlet
## 2 Ernest Hemingway Hamlet
## 3 Thomas Mann Hamlet
## 4 William Shakespeare The Old Man and the Sea
## 5 Ernest Hemingway The Old Man and the Sea
## 6 Thomas Mann The Old Man and the Sea
## 7 William Shakespeare Reflections of an Unpolitical Man
## 8 Ernest Hemingway Reflections of an Unpolitical Man
## 9 Thomas Mann Reflections of an Unpolitical Man
is(x)
## [1] "data.frame" "list" "oldClass" "vector"
With the following structure:
str(x)
## 'data.frame': 9 obs. of 2 variables:
## $ Var1: chr "William Shakespeare" "Ernest Hemingway" "Thomas Mann" "William Shakespeare" ...
## $ Var2: chr "Hamlet" "Hamlet" "Hamlet" "The Old Man and the Sea" ...
## - attr(*, "out.attrs")=List of 2
## ..$ dim : num 3 3
## ..$ dimnames:List of 2
## .. ..$ Var1: chr "Var1=William Shakespeare" "Var1=Ernest Hemingway" "Var1=Thomas Mann"
## .. ..$ Var2: chr "Var2=Hamlet" "Var2=The Old Man and the Sea" "Var2=Reflections of an Unpolitical Man"
To learn more about the expand.grid function, type in the console:
?expand.grid