Looking to add a Time Period column to my data frame

Hello,

I'm currently working with some data that comes in 250 unique observations and I'm trying to add a new column to my data frame called "time period" where the observations are grouped into sections of 50, meaning observations 1-50 will have a 1 in the time period column, 51-100 will have a 2, and so on. I know that I have to use mutate to create the new column, but after that I am lost as to how to go about doing this. Any help would be greatly appreciated. Thanks.

I would make a row number column and then use integer division to label the time periods.

library(dplyr)
DF <- data.frame(Name = paste0("A", 1:250), Value = rnorm(250))
head(DF)
#>   Name       Value
#> 1   A1 -0.08143561
#> 2   A2 -0.88270571
#> 3   A3 -1.29096226
#> 4   A4  0.56884325
#> 5   A5 -1.13031989
#> 6   A6  0.10579915
DF <- DF %>% mutate(Row = row_number() - 1, time_period = Row %/% 50 + 1) %>% select(-Row)
head(DF)
#>   Name       Value time_period
#> 1   A1 -0.08143561           1
#> 2   A2 -0.88270571           1
#> 3   A3 -1.29096226           1
#> 4   A4  0.56884325           1
#> 5   A5 -1.13031989           1
#> 6   A6  0.10579915           1
DF[48:52, ]
#>    Name     Value time_period
#> 48  A48 0.3865449           1
#> 49  A49 0.6577830           1
#> 50  A50 0.9418441           1
#> 51  A51 0.2948318           2
#> 52  A52 0.5437474           2
tail(DF)
#>     Name        Value time_period
#> 245 A245 -1.642056220           5
#> 246 A246  0.185185495           5
#> 247 A247  0.142535434           5
#> 248 A248  0.169160255           5
#> 249 A249  0.736191847           5
#> 250 A250 -0.005219281           5

Created on 2019-12-02 by the reprex package (v0.2.1)

2 Likes

That worked perfectly. Thank you so much!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.