Assign a sequence of numbers to data frame rows

Viewed 217

I am trying to assign a sequence of numbers to rows in a data frame based off of the row position. I have 330 rows and I want each set of nine rows to be named one through nine in a new ID column. For example, I want rows 1-9 labeled 1-9, rows 10-18 labeled 1-9, rows 19-27 labeled 1-9 and so on.

I have tried to use this code:

test <- temp.df %>% mutate(id = seq(from = 1, to = 330, along.width= 9))
test

but it just ends up just creating a new column that labels the rows 1-330 as shown below.

Time        Temperature    ID
09:36:52    25.4           1
09:36:59    25.4           2
09:37:07    25.4           3
09:37:14    25.4           4
09:37:21    25.4           5
09:37:29    25.4           6
09:37:36    25.4           7
09:37:43    25.5           8
09:37:51    25.5           9
09:37:58    25.5          10

What is the best way to accomplish my goal?

1 Answers

I think if you could provide a snippet of the data.frame temp.df, it would be easier to help you out. Maybe the following line could help you by adding it to your data.frame, however, it is not a very flexible solution, but it is based on the information you provided.

n_repeated <- 9    #block of ID
N_rows   <- 330    #number of observations

df <- data.frame(id = rep(seq(1,n_repeated ),N_rows ))

head(df,n = 15)

#> head(df,n = 15)
#   id
# 1   1
# 2   2
# 3   3
# 4   4
# 5   5
# 6   6
# 7   7
# 8   8
# 9   9
# 10  1
# 11  2
# 12  3
# 13  4
# 14  5
# 15  6

[Edited]

using mutate from dplyr this line should do it:

test <- temp.df %>% mutate(id = rep(seq(1,9), nrow(temp.df)))
Related