如何将组扩展到最大组的长度:
df <- structure(list(ID = c(1L, 1L, 2L, 3L, 3L, 3L), col1 = c("A",
"B", "O", "U", "L", "R")), class = "data.frame", row.names = c(NA,
-6L))
ID col1
1 A
1 B
2 O
3 U
3 L
3 R
Run Code Online (Sandbox Code Playgroud)
期望的输出:
1 A
1 B
NA NA
2 O
NA NA
NA NA
3 U
3 L
3 R
Run Code Online (Sandbox Code Playgroud)
您可以利用df[n_bigger_than_nrow,]给出一排NAs的事实
dplyr
\nmax_n <- max(count(df, ID)$n)\n\ndf %>% \n group_by(ID) %>% \n summarise(cur_data()[seq(max_n),])\n#> `summarise()` has grouped output by \'ID\'. You can override using the `.groups`\n#> argument.\n#> # A tibble: 9 \xc3\x97 2\n#> # Groups: ID [3]\n#> ID col1 \n#> <int> <chr>\n#> 1 1 A \n#> 2 1 B \n#> 3 1 <NA> \n#> 4 2 O \n#> 5 2 <NA> \n#> 6 2 <NA> \n#> 7 3 U \n#> 8 3 L \n#> 9 3 R\nRun Code Online (Sandbox Code Playgroud)\n碱基R
\nn <- tapply(df$ID, df$ID, length)\nmax_n <- max(n)\ni <- lapply(n, \\(x) c(seq(x), rep(Inf, max_n - x)))\ni <- Map(`+`, i, c(0, cumsum(head(n, -1))))\ndf <- df[unlist(i),]\nrownames(df) <- NULL\ndf$ID <- rep(as.numeric(names(i)), each = max_n)\n\ndf\n#> ID col1\n#> 1 1 A\n#> 2 1 B\n#> 3 1 <NA>\n#> 4 2 O\n#> 5 2 <NA>\n#> 6 2 <NA>\n#> 7 3 U\n#> 8 3 L\n#> 9 3 R\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
556 次 |
| 最近记录: |