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

Time:11-07

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:

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!

CodePudding user response:

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

CodePudding user response:

Using rep to repeat elements individually, then put them in a data frame.

data.frame(x = rep(x[, 1], each=nrow(y)), y = y[, 1])
  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
  •  Tags:  
  • r
  • Related