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

R: How do I add a column with values to a table, for every row in said table?

For example, if I have two lists:

x <- data.frame(c('a', 'b', 'c'))
y <- data.frame(c('1', '2', '3'))

I want my output to look like:

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

x y
a 1
a 2
a 3
b 1
b 2
b 3
c 1
c 2
c 3

I sadly have no idea how such an operation is called, or where to start. Could anyone help me with a solution? Thanks!

>Solution :

Here are a few options:

library(tidyverse)

x <- data.frame(x = c('a', 'b', 'c')) 
y <- data.frame(y = c('1', '2', '3'))

#option 1
expand.grid(x = x$x, y = y$y) |>
  arrange(x)
#>   x y
#> 1 a 1
#> 2 a 2
#> 3 a 3
#> 4 b 1
#> 5 b 2
#> 6 b 3
#> 7 c 1
#> 8 c 2
#> 9 c 3

#option 2 
map_dfr(x$x, ~tibble(x = .x, y = y$y))
#> # A tibble: 9 x 2
#>   x     y    
#>   <chr> <chr>
#> 1 a     1    
#> 2 a     2    
#> 3 a     3    
#> 4 b     1    
#> 5 b     2    
#> 6 b     3    
#> 7 c     1    
#> 8 c     2    
#> 9 c     3

#option 3
full_join(x, y, by = character())
#>   x y
#> 1 a 1
#> 2 a 2
#> 3 a 3
#> 4 b 1
#> 5 b 2
#> 6 b 3
#> 7 c 1
#> 8 c 2
#> 9 c 3
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