Here is a possible tidyverse
solution. We can use add_row
inside of summarise
to add n number of rows to each group. I use max(count(df, ID)$n)
to get the max group length, then I subtract that from the number of rows in each group to get the total number of rows that need to be added for each group. I use rep
to produce the correct number of values that we need to add for each group. Finally, I replace ID
with NA
when there is an NA
in col1
.
library(tidyverse)
df %>%
group_by(ID) %>%
summarise(add_row(cur_data(),
col1 = rep(NA_character_,
unique(max(count(df, ID)$n) - n()))),
.groups = "drop") %>%
mutate(ID = replace(ID, is.na(col1), NA))
Output
ID col1
<int> <chr>
1 1 A
2 1 B
3 NA NA
4 2 O
5 NA NA
6 NA NA
7 3 U
8 3 L
9 3 R
Or another option without using add_row
:
library(dplyr)
# Get maximum number of rows for all groups
N = max(count(df,ID)$n)
df %>%
group_by(ID) %>%
summarise(col1 = c(col1, rep(NA, N-length(col1))), .groups = "drop") %>%
mutate(ID = replace(ID, is.na(col1), NA))
dplyr
solution, but there's adata.table
solution