Home > Back-end >  Adding longer vectors to unique identifiers in R
Adding longer vectors to unique identifiers in R

Time:07-28

I have a couple numeric IDs which I am trying to bind time values and labels to the time values. Here is a reprex of what I am working with:

ID=data.frame(id=c(1,2))
time=c(seq(0,168,24))
label=c("Sample1","Sample2","Sample3","Sample4","Sample5","Sample6","Sample7","Sample8")

This is my current code, which produces the following result:

df=ID %>% 
cbind(.,data.frame(time=time, label=label))

print(df)

  id time   label
1  1    0 Sample1
2  2   24 Sample2
3  1   48 Sample3
4  2   72 Sample4
5  1   96 Sample5
6  2  120 Sample6
7  1  144 Sample7
8  2  168 Sample8

What I am aiming for is this:

   id time  label
1   1    0  Sample1
2   1   24  Sample2
3   1   48  Sample3
4   1   72  Sample4
5   1   96  Sample5
6   1  120  Sample6
7   1  144  Sample7
8   1  168  Sample8
9   2    0  Sample1
10  2   24  Sample2
11  2   48  Sample3
12  2   72  Sample4
13  2   96  Sample5
14  2  120  Sample6
15  2  144  Sample7
16  2  168  Sample8

Any help is appreciated!

CodePudding user response:

You can use expand.grid()

expand.grid(Time=time, ID=ID$id) |> cbind(label)

   Time ID   label
1     0  1 Sample1
2    24  1 Sample2
3    48  1 Sample3
4    72  1 Sample4
5    96  1 Sample5
6   120  1 Sample6
7   144  1 Sample7
8   168  1 Sample8
9     0  2 Sample1
10   24  2 Sample2
11   48  2 Sample3
12   72  2 Sample4
13   96  2 Sample5
14  120  2 Sample6
15  144  2 Sample7
16  168  2 Sample8
  • Related