- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a data frame with combinations of values in R?
Suppose we have two values 0 and 1 then how many combinations of these values are possible, the answer is 8 and these combinations are (0,0), (1,0), (0,1), (1,1). In R, we can use expand.grid function to create these combinations but to save it in a data frame, we would need to use as.data.frame function.
Example
df1<-as.data.frame(expand.grid(c(0,1),c(0,1))) df1
Output
Var1 Var2 1 0 0 2 1 0 3 0 1 4 1 1
Example
df2<-as.data.frame(expand.grid(c(0,1),c(0,1),c(0,1))) df2
Output
Var1 Var2 Var3 1 0 0 0 2 1 0 0 3 0 1 0 4 1 1 0 5 0 0 1 6 1 0 1 7 0 1 1 8 1 1 1
Example
df3<-as.data.frame(expand.grid(c(0,1,2),c(0,1,2),c(0,1,2))) df3
Output
Var1 Var2 Var3 1 0 0 0 2 1 0 0 3 2 0 0 4 0 1 0 5 1 1 0 6 2 1 0 7 0 2 0 8 1 2 0 9 2 2 0 10 0 0 1 11 1 0 1 12 2 0 1 13 0 1 1 14 1 1 1 15 2 1 1 16 0 2 1 17 1 2 1 18 2 2 1 19 0 0 2 20 1 0 2 21 2 0 2 22 0 1 2 23 1 1 2 24 2 1 2 25 0 2 2 26 1 2 2 27 2 2 2
Example
df4<-as.data.frame(expand.grid(c(0,1,2),c(0,1,2))) df4
Output
Var1 Var2 1 0 0 2 1 0 3 2 0 4 0 1 5 1 1 6 2 1 7 0 2 8 1 2 9 2 2
Example
df5<-as.data.frame(expand.grid(c(1,2),c(1,2),c(1,2))) df5
Output
Var1 Var2 Var3 1 1 1 1 2 2 1 1 3 1 2 1 4 2 2 1 5 1 1 2 6 2 1 2 7 1 2 2 8 2 2 2
- Related Articles
- How to create a clone of a data frame in R without data values?
- How to create a data frame with a column having repeated values in R?
- How to create a vector of data frame values by rows in R?
- Find the unique pair combinations of an R data frame column values.
- How to create a character vector from data frame values in R?
- How to create combinations of 0 and 1 with fixed number of 1s in each row in an R data frame?
- How to create a data frame in R with list elements?
- How to create a column with the serial number of values in character column of an R data frame?
- How to split a data frame in R with conditional row values?
- How to create a data frame column with equally spaced values between 0 and 1 in R?
- How to create a repeated values column with each value in output selected randomly in R data frame?
- How to create a data frame column with letters of both size in R?
- How to create barplot for some top values in an R data frame?
- How to create a table of frequency for range of values in an R data frame column?
- How to multiply vector values in sequence with columns of a data frame in R?

Advertisements