R 以表格形式显示嵌套在另一列下的一列
我在一个数据框中有两列,存储编号(113个值)和存储“所属”的集群编号,该集群编号有六个值(1-6): pct_v2[c(“门店号”、“集团pct”)] 我想创建一个表,其中group_pct值为列,单元格条目为StoreNumber列的值:R 以表格形式显示嵌套在另一列下的一列,r,R,我在一个数据框中有两列,存储编号(113个值)和存储“所属”的集群编号,该集群编号有六个值(1-6): pct_v2[c(“门店号”、“集团pct”)] 我想创建一个表,其中group_pct值为列,单元格条目为StoreNumber列的值: Group_pct 2 3 4 5 6 -------------------------------
Group_pct
2 3 4 5 6
----------------------------------------------
1 2 4 5 9
20 6 12 10
23
这可以在tidyverse中完成吗?pct
pct <- structure(list(StoreNumber = c(1L, 2L, 4L, 5L, 6L, 9L, 10L, 12L, 20L, 23L), groups_pct = c(1L, 2L, 3L, 4L, 2L, 5L, 5L, 4L, 1L, 4L), i = 1:10), .Names = c("StoreNumber", "groups_pct", "i"), row.names = c(NA, -10L), class = "data.frame")
pct <- structure(list(StoreNumber = c(1L, 2L, 4L, 5L, 6L, 9L, 10L, 12L, 20L, 23L), groups_pct = c(1L, 2L, 3L, 4L, 2L, 5L, 5L, 4L, 1L, 4L), i = 1:10), .Names = c("StoreNumber", "groups_pct", "i"), row.names = c(NA, -10L), class = "data.frame")
library(tidyr)
pct$i <- 1:10 # required for spread, then discarded with [-1]
pct2 <- lapply(spread(pct, groups_pct, StoreNumber)[-1], na.omit)
str(pct2)
# List of 5
# $ 1: atomic [1:2] 1 20
# ..- attr(*, "na.action")=Class 'omit' int [1:8] 2 3 4 5 6 7 8 10
# $ 2: atomic [1:2] 2 6
# ..- attr(*, "na.action")=Class 'omit' int [1:8] 1 3 4 6 7 8 9 10
# $ 3: atomic [1:1] 4
# ..- attr(*, "na.action")=Class 'omit' int [1:9] 1 2 4 5 6 7 8 9 10
# $ 4: atomic [1:3] 5 12 23
# ..- attr(*, "na.action")=Class 'omit' int [1:7] 1 2 3 5 6 7 9
# $ 5: atomic [1:2] 9 10
# ..- attr(*, "na.action")=Class 'omit' int [1:8] 1 2 3 4 5 8 9 10
pct3 <- lapply(pct2, function(l) c(l, rep(NA, max(lengths(pct2))-length(l))))
str(pct3)
# List of 5
# $ 1: int [1:3] 1 20 NA
# $ 2: int [1:3] 2 6 NA
# $ 3: int [1:3] 4 NA NA
# $ 4: int [1:3] 5 12 23
# $ 5: int [1:3] 9 10 NA
as.data.frame(pct3)
# X1 X2 X3 X4 X5
# 1 1 2 4 5 9
# 2 20 6 NA 12 10
# 3 NA NA NA 23 NA