I have this dataframe
and I want this result
For each group I want to fill from day 1 to day 6.
Which is the code?
I have this dataframe
and I want this result
For each group I want to fill from day 1 to day 6.
Which is the code?
Here are two methods.
#Methoc 1. Every Group has 6 members
DF <- data.frame(Group = rep(c("A","B","C","D"), each = 6),
Day = NA)
DF
#> Group Day
#> 1 A NA
#> 2 A NA
#> 3 A NA
#> 4 A NA
#> 5 A NA
#> 6 A NA
#> 7 B NA
#> 8 B NA
#> 9 B NA
#> 10 B NA
#> 11 B NA
#> 12 B NA
#> 13 C NA
#> 14 C NA
#> 15 C NA
#> 16 C NA
#> 17 C NA
#> 18 C NA
#> 19 D NA
#> 20 D NA
#> 21 D NA
#> 22 D NA
#> 23 D NA
#> 24 D NA
DF$Day <- rep(1:6, times = 4)
DF
#> Group Day
#> 1 A 1
#> 2 A 2
#> 3 A 3
#> 4 A 4
#> 5 A 5
#> 6 A 6
#> 7 B 1
#> 8 B 2
#> 9 B 3
#> 10 B 4
#> 11 B 5
#> 12 B 6
#> 13 C 1
#> 14 C 2
#> 15 C 3
#> 16 C 4
#> 17 C 5
#> 18 C 6
#> 19 D 1
#> 20 D 2
#> 21 D 3
#> 22 D 4
#> 23 D 5
#> 24 D 6
#Method 2, Groups do not have to have the same number of members
library(dplyr)
DF <- data.frame(Group = rep(c("A","B","C","D"), each = 6),
Day = NA)
DF <- DF |> group_by(Group) |> mutate(Day = row_number())
DF
#> # A tibble: 24 × 2
#> # Groups: Group [4]
#> Group Day
#> <chr> <int>
#> 1 A 1
#> 2 A 2
#> 3 A 3
#> 4 A 4
#> 5 A 5
#> 6 A 6
#> 7 B 1
#> 8 B 2
#> 9 B 3
#> 10 B 4
#> # … with 14 more rows
Created on 2023-03-23 with reprex v2.0.2
Here is an approach that leaves the groups and number of times to repeat them flexible:
library(dplyr)
grps <- c('A','B','C','D')
reps <- 6
DF <- data.frame(
Group = rep(grps, reps) %>% sort(.)
) %>%
group_by(Group) %>%
mutate(
Day = seq(1:reps)
) %>%
ungroup(.)
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.