如何将 pivot_wider 个结果分成几行

How to separate pivot_wider results into rows

我有这个df

structure(list(uniqueID = c(1512211, 1512211, 1512211, 58211, 
58211, 58211, 58211), food_item = c("sp2", "sp3", "sp4", "sp10", 
"sp3", "sp4", "sp5"), points = c(10, 3, 20, 2, 3, 4, 3)), spec = structure(list(
    cols = list(uniqueID = structure(list(), class = c("collector_double", 
    "collector")), food_item = structure(list(), class = c("collector_character", 
    "collector")), points = structure(list(), class = c("collector_double", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
    "collector")), delim = ";"), class = "col_spec"), row.names = c(NA, 
-7L), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"))

我正在尝试转换成这样的 table,其中每个点分布在行中,“SP”单独标记这些点,每个 SP 之间没有重叠。

我做了这个代码但是没有用

an_anj <- an_anj %>%
    filter(uniqueID == "1512211") %>% 
  pivot_wider(names_from = food_item,
              values_from = points, 
              values_fill = 0) %>% 
uncount(points)

错误:mutate()_weight 有问题。 我_weight = points。 x _weight 必须是向量,而不是函数。 i 错误发生在第 1 组:uniqueID = "anjos1512211"。 运行rlang::last_error()查看哪里出错了

当我做的时候

an_anj <- an_anj %>%
    filter(uniqueID == "1512211") %>% 
  pivot_wider(names_from = food_item,
              values_from = points, 
              values_fill = 0)

我没有得到单独的行

我们可能 uncount 在执行 pivot_wider

之前复制行
library(dplyr)
library(data.table)
library(tidyr)
out <- an_anj %>%
    filter(uniqueID == "1512211") %>%
    mutate(new = 1) %>% 
    uncount(points) %>%
    mutate(rn = rowid(uniqueID)) %>%
    pivot_wider(names_from = food_item, values_from = new, 
          values_fill = 0) %>% 
   select(-rn)

-输出

> as.data.frame(out)
   uniqueID sp2 sp3 sp4
1   1512211   1   0   0
2   1512211   1   0   0
3   1512211   1   0   0
4   1512211   1   0   0
5   1512211   1   0   0
6   1512211   1   0   0
7   1512211   1   0   0
8   1512211   1   0   0
9   1512211   1   0   0
10  1512211   1   0   0
11  1512211   0   1   0
12  1512211   0   1   0
13  1512211   0   1   0
14  1512211   0   0   1
15  1512211   0   0   1
16  1512211   0   0   1
17  1512211   0   0   1
18  1512211   0   0   1
19  1512211   0   0   1
20  1512211   0   0   1
21  1512211   0   0   1
22  1512211   0   0   1
23  1512211   0   0   1
24  1512211   0   0   1
25  1512211   0   0   1
26  1512211   0   0   1
27  1512211   0   0   1
28  1512211   0   0   1
29  1512211   0   0   1
30  1512211   0   0   1
31  1512211   0   0   1
32  1512211   0   0   1
33  1512211   0   0   1