如何在数据集中搜索特定 ID 并将相邻单元格中的值报告到新列中

How to search in datasets for specific IDs and report values from the neighboring cell into new column(s)

我有一个与此类似的数据集(显然大得多):

    ID <- c(1,2,3,4,5,6)
    MASS <- c(324,162,508,675,670,832)
    DIFF <- c("2","1","5","0","3&6","5")
    d <- data.frame(ID, MASS, DIFF)

  ID MASS DIFF
1  1  324    2
2  2  162    1
3  3  508    5
4  4  675    0
5  5  670  3&6
6  6  832    5

在 R 中是否有任何方法可以设置一个脚本:

目的是获得类似于下面报告的内容,我希望这可以澄清我对问题的笨拙描述:

  ID MASS DIFF MASS1 MASS2
1  1  324    2   162    NA
2  2  162    1   324    NA
3  3  508    5   670    NA
4  4  675    0    NA    NA
5  5  670  3&6   508   832
6  6  832    5   670    NA

非常感谢任何建议

这感觉很老套而且过于复杂,但它确实有效。也许其他人有更有效的方法:

library(dplyr)
library(tidyr)
library(purrr)

d |> 
  separate_rows(DIFF, convert = TRUE) |> 
  left_join(d, c("DIFF" = "ID")) |>
  select(-DIFF.y) |> 
  group_by(ID) |> 
  mutate(DIFF = paste(DIFF, collapse = "&")) |> 
  ungroup() |> 
  rename(MASS = MASS.x) |> 
  group_split(ID) |> 
  map(~ .x |>
        mutate(temp = row_number()) |> 
        pivot_wider(values_from = MASS.y, names_from = temp, names_glue = "MASS{temp}")) |> 
  bind_rows()

# A tibble: 6 × 5
     ID  MASS DIFF  MASS1 MASS2
  <dbl> <dbl> <chr> <dbl> <dbl>
1     1   324 2       162    NA
2     2   162 1       324    NA
3     3   508 5       670    NA
4     4   675 0        NA    NA
5     5   670 3&6     508   832
6     6   832 5       670    NA