Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a dataframe by fixing rows in one column and repeating other columns

Lets say I have three variables:

var1<-c(101,102,103,104)
var2<-c("AB","XY")
var3<-c(1,2)

X<-expand.grid(var1,var2,var3)
X

Above code gives this output

   Var1 Var2 Var3
1   101   AB    1
2   102   AB    1
3   103   AB    1
4   104   AB    1
5   101   XY    1
6   102   XY    1
7   103   XY    1
8   104   XY    1
9   101   AB    2
10  102   AB    2
11  103   AB    2
12  104   AB    2
13  101   XY    2
14  102   XY    2
15  103   XY    2
16  104   XY    2

What I need is the series below in which for each row value in var1 we have corresponding values in var2 and var3.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   Var1 Var2 Var3
1   101  AB  1
2   101  XY  2
3   102  AB  1
4   102  XY  2
5   103  AB  1
6   103  XY  2
7   104  AB  1
8   104  XY  2

>Solution :

If you are already using the tidyr package, you can use the crossing function. For example

tidyr::crossing(var1, tibble::tibble(var2, var3))
#    var1 var2   var3
#   <dbl> <chr> <dbl>
# 1   101 AB        1
# 2   101 XY        2
# 3   102 AB        1
# 4   102 XY        2
# 5   103 AB        1
# 6   103 XY        2
# 7   104 AB        1
# 8   104 XY        2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading