我想将 R 数据框转换为带有列表列的数据框

I want to transform an R dataframe into a dataframe with a column of list

好的,我有一个两列 data.frame,可变数量为 childhead。 (其他2列为参考)

dat <- read.table(header=TRUE, stringsAsFactors=FALSE, text="
                        head          child UID     logic
                    1  01001         01001   1     FALSE
                    2  01001         01021   2      TRUE
                    3  01001         01047   3      TRUE
                    4  01001         01051   4      TRUE
                    5  01001         01085   5      TRUE
                    6  01001         01101   6      TRUE
                    7  01003         01003   7     FALSE
                    8  01003         01025   8      TRUE
                    9  01003         01053   9      TRUE
                    10 01003         01097  10      TRUE
                    11 01003         01099  11      TRUE
                    12 01003         01129  12      TRUE
                    13 01003         12033  13      TRUE
                    14 01005         01005  14     FALSE
                    15 01005         01011  15      TRUE
                    16 01005         01045  16      TRUE
                    17 01005         01067  17      TRUE
                    18 01005         01109  18      TRUE
                    19 01005         01113  19      TRUE
                    20 01005         13061  20      TRUE
                    21 01005         13239  21      TRUE
                    22 01005         13259  22      TRUE")

我想只有三行用于唯一 head 和一个列表用于 child

如果您有更好的方法建议,我愿意接受。

其他栏目UIDlogic是我添加的参考,但可以删除。

在我的尝试中,我尝试转换为带有边列表的图形,然后转换为 JSON。

# make graph ##########
library(tidyverse)
library(igraph)
library(jsonlite)
gdat <- select(dat, head, child)
mdat <- as.matrix(gdat)
edge_dat <- graph_from_edgelist(mdat)
plot.igraph(edge_dat)
jdat <- toJSON(mdat, matrix = "rowmajor")

期望的输出:

head   child1   child2   child3   child4   child5   child6   child7
01001  01001    01021    01047    01051    01085    01101    NA
01003  01003    01025    01053    ... and so on
01005  01005    01011    ... and so on

是你想要的吗?

setDT(dat)

dat_child <- dat[(logic)]
dat_child[,.(list(unique(child))), by = "head"]

dat_child
   head                                      V1
1: 1001                1021,1047,1051,1085,1101
2: 1003      1025, 1053, 1097, 1099, 1129,12033
3: 1005  1011, 1045, 1067, 1109, 1113,13061,...