在更宽的数据透视表中的单独行上显示重复值

Show duplicate value on a separate row in pivot wider

我看过很多答案,但无法正确回答。基本上我想在执行更宽的数据透视表时在单独的行上显示 duplciate。我也创建了一个唯一的变量,但结果是每列的嵌套行或单独的行。

df <- structure(list(identifier = c("e1", "e1", "e2", "e2", "e1", "e1", 
"e1", "e1", "e2", "e2"), label = c("Monaco", "became", "the", 
"first", "the", "the", "Monaco", "became", "the", "first"), id = c("CP1", 
"CP1", "CP1", "CP1", "CP1", "CP1", "CP2", "CP2", "CP2", "CP2"
), value = c(0L, 0L, 1L, 0L, 10L, 1L, 1L, 0L, 1L, 0L)), class = "data.frame", row.names = c(NA, 
-10L))

library(tidyverse)

#My try 

df %>%
group_by(identifier,label) %>% 
mutate(rn=row_number()) %>% 
  pivot_wider(  names_from="id",
              values_from="value")

你可以使用-

library(dplyr)
library(tidyr)

df %>%
  pivot_wider(names_from=id,values_from=value, values_fn = list) %>%
  unnest(cols = c(CP1, CP2))

#  identifier label    CP1   CP2
#  <chr>      <chr>  <int> <int>
#1 e1         Monaco     0     1
#2 e1         became     0     0
#3 e2         the        1     1
#4 e2         first      0     0
#5 e1         the       10    NA
#6 e1         the        1    NA

您的尝试也很接近,您必须在 group_by -

中包含 id
df %>%
  group_by(identifier,label, id) %>% 
  mutate(rn=row_number()) %>% 
  pivot_wider(names_from=id,values_from=value)
library(data.table)
library(tidyr)
unnest( dcast(setDT(df), identifier + label ~ id, value.var = "value", 
              fill = NA, fun.aggregate = list), cols = c("CP1", "CP2"))
# # A tibble: 6 x 4
#   identifier label    CP1   CP2
#   <chr>      <chr>  <int> <int>
# 1 e1         Monaco     0     1
# 2 e1         became     0     0
# 3 e1         the       10    NA
# 4 e1         the        1    NA
# 5 e2         first      0     0
# 6 e2         the        1     1