Home > Net >  Add a column and repeat every 16 dplyr
Add a column and repeat every 16 dplyr

Time:06-08

I need to add a column, column name "type", and for every 16 rows, change the row name to "type1, type 2 etc".
I tried book1$ID %/% 16 but not quite right. This is the original data:

book1 <- structure(list(ID = 1:34, per_section = c(1L, 2L, 3L, 4L, 5L, 
6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L, 2L, 3L, 
4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L, 
2L)), class = "data.frame", row.names = c(NA, -34L))

This is my desired output:

output <- structure(list(ID = 1:34, Type = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L), per_section = c(1L, 
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 
16L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 
14L, 15L, 16L, 1L, 2L)), class = "data.frame", row.names = c(NA, 
-34L))

CodePudding user response:

With %/% we may need to adjust by subtracting 1 and adding 1

book1$Type <- with(book1, (ID-1) %/% 16   1)

Or maybe more easier with gl

library(dplyr)
book1 <- book1 %>%
   mutate(Type = as.integer(gl(n(), 16, n())), .after = 1)

CodePudding user response:

Try this

book1$type <-ifelse(1:nrow(book1) %% 16 != 0 , 
                    1:nrow(book1) %% 16 , 16) 
  • Related