0

I currently have a data frame that looks like

Trial # Header Header 2 Header 3
1 1 1.1 1.2
2 2 2.1 2.2
3 3 3.1 3.2
4 4 4.1 4.2

And I need to add mutate the data frame so there is a year column and each trial repeats 3 times. Something that looks like:

Trial # Header Header 2 Header 3 Year
1 1 1.1 1.2 1
1 1 1.1 1.2 2
1 1 1.1 1.2 3
2 2 2.1 2.2 1
2 2 2.1 2.2 2
2 2 2.1 2.2 3
3 3 3.1 3.2 1
3 3 3.1 3.2 2
3 3 3.1 3.2 3
4 4 4.1 4.2 1
4 4 4.1 4.2 2
4 4 4.1 4.2 3

I am not sure how to go about accomplishing this so any help is appreciated!

PythonSOS
  • 339
  • 5
  • 16

2 Answers2

2

Very directly, you can do this:

result = original_data[rep(1:nrow(original_data, each = 3), ]
result$year = rep(1:3, times = nrow(original_data))

A little fancier, and more generalizable if you had additional columns you wanted combinations of, we can use merge to do a cross join.

result = merge(original_data, data.frame(year = 1:3), all = TRUE)
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • I believe `merge(df, list(year=1:3))` should also work – Onyambu Nov 11 '21 at 20:26
  • When I do that, the resulting data frame is grouped by year. How do I get it so that it is grouped by trial number instead? – PythonSOS Nov 11 '21 at 20:31
  • @PythonSOS No the data is in no way grouped. It is just arranged. Not grouped. and there is nothing wrong if arranged by year or Trial number. All the resulting computation will be the same. Just order it by Trial Number, ie `with(a<-merge(df, list(year =1:3)), a[order(Trial), ])` – Onyambu Nov 11 '21 at 20:37
1
df %>%
  mutate(year = list(1:3))%>%
  unnest(year)

# A tibble: 12 x 5
   Trial Header Header.2 Header.3  year
   <int>  <int>    <dbl>    <dbl> <int>
 1     1      1      1.1      1.2     1
 2     1      1      1.1      1.2     2
 3     1      1      1.1      1.2     3
 4     2      2      2.1      2.2     1
 5     2      2      2.1      2.2     2
 6     2      2      2.1      2.2     3
 7     3      3      3.1      3.2     1
 8     3      3      3.1      3.2     2
 9     3      3      3.1      3.2     3
10     4      4      4.1      4.2     1
11     4      4      4.1      4.2     2
12     4      4      4.1      4.2     3
Onyambu
  • 67,392
  • 3
  • 24
  • 53