nc97
nc97

Reputation: 1

Add rows to dataframe in R based on values in column

I have a dataframe with 2 columns: time and day. there are 3 days and for each day, time runs from 1 to 12. I want to add new rows for each day with times: -2, 1 and 0. How do I do this? I have tried using add_row and specifying the row number to add to, but this changes each time a new row is added making the process tedious. Thanks in advance picture of the dataframe

Upvotes: 0

Views: 1865

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 389235

You can use tidyr::crossing

library(dplyr)
library(tidyr)

add_values <- c(-2, 1, 0)

crossing(time = add_values, Day = unique(day$Day)) %>%
  bind_rows(day) %>%
  arrange(Day, time)

# A tibble: 45 x 2
#    time   Day
#   <dbl> <int>
# 1    -2     1
# 2     0     1
# 3     1     1
# 4     1     1
# 5     2     1
# 6     3     1
# 7     4     1
# 8     5     1
# 9     6     1
#10     7     1
# … with 35 more rows

If you meant -2, -1 and 0 you can also use complete.

tidyr::complete(day, Day, time = -2:0)

Upvotes: 0

TarJae
TarJae

Reputation: 79204

We could use add_row then slice the desired sequence and bind all to a dataframe:

library(tibble)
library(dplyr)

df1 <- df %>% 
  add_row(time  = -2:0, Day = c(1,1,1), .before = 1) %>% 
  slice(1:15)

df2 <-  bind_rows(df1, df1, df1) %>% 
  mutate(Day = rep(row_number(), each=15, length.out = n()))

Output:

# A tibble: 45 x 2
    time   Day
   <dbl> <int>
 1    -2     1
 2    -1     1
 3     0     1
 4     1     1
 5     2     1
 6     3     1
 7     4     1
 8     5     1
 9     6     1
10     7     1
11     8     1
12     9     1
13    10     1
14    11     1
15    12     1
16    -2     2
17    -1     2
18     0     2
19     1     2
20     2     2
21     3     2
22     4     2
23     5     2
24     6     2
25     7     2
26     8     2
27     9     2
28    10     2
29    11     2
30    12     2
31    -2     3
32    -1     3
33     0     3
34     1     3
35     2     3
36     3     3
37     4     3
38     5     3
39     6     3
40     7     3
41     8     3
42     9     3
43    10     3
44    11     3
45    12     3

Upvotes: 1

user16051136
user16051136

Reputation:

Here's a fast way to create the desired dataframe from scratch using expand.grid(), rather than adding individual rows:

df <- expand.grid(-2:12,1:3)
colnames(df) <- c("time","day")

Results:

df
   time day
1    -2   1
2    -1   1
3     0   1
4     1   1
5     2   1
6     3   1
7     4   1
8     5   1
9     6   1
10    7   1
11    8   1
12    9   1
13   10   1
14   11   1
15   12   1
16   -2   2
17   -1   2
18    0   2
19    1   2
20    2   2
21    3   2
22    4   2
23    5   2
24    6   2
25    7   2
26    8   2
27    9   2
28   10   2
29   11   2
30   12   2
31   -2   3
32   -1   3
33    0   3
34    1   3
35    2   3
36    3   3
37    4   3
38    5   3
39    6   3
40    7   3
41    8   3
42    9   3
43   10   3
44   11   3
45   12   3

Upvotes: 0

Related Questions