在R中将数据框转换为列表的列表

3

我希望将这个类似于 data.frame 的数据结构转换为:

dat = data.frame (
    ConditionA = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
    ConditionB = c(1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5),
    X = c(460, 382, 468, 618, 421, 518, 655, 656, 621, 552, 750, 725, 337, 328, 342, 549, 569, 523, 469, 429),
    Y = c(437, 305, 498, 620, 381, 543, 214, 181, 183, 387, 439, 351, 327, 268, 276, 178, 375, 393, 312, 302)
)

将其转换为如下列表(或类似)的列表:
lst = list(
    list(
        c(460, 382, 468, 618),
        c(437, 305, 498, 620)
    ),
    list(
        c(421, 518, 655, 656, 621),
        c(381, 543, 214, 181, 183)
    ),
    list(
        c(552, 750, 725),
        c(387, 439, 351)
    ),
    list(
        c(337, 328, 342, 549),
        c(327, 268, 276, 178)
    ),
    list(
        c(569, 523, 469, 429),
        c(375, 393, 312, 302)
    )
)

> lst
[[1]]
[[1]][[1]]
[1] 460 382 468 618

[[1]][[2]]
[1] 437 305 498 620


[[2]]
[[2]][[1]]
[1] 421 518 655 656 621

[[2]][[2]]
[1] 381 543 214 181 183


[[3]]
[[3]][[1]]
[1] 552 750 725

[[3]][[2]]
[1] 387 439 351

. . .

什么是最有效的方法来进行这样的转换?

3
为什么有两个 ConditionA?假设只有一个:lapply(split(dat[, c("X", "Y")], dat$ConditionA), as.list) - Alexis
@Alexis 我在回答时没有看到你的评论。 - akrun
3个回答

4
我们可以根据第一列和第二列进行分割,使用drop=TRUE来删除元素为0的组合,并将其转换为list
lapply(split(dat[-(1:2)], dat[1:2], drop = TRUE), as.list)

或者使用tidyverse

library(tidyverse)
dat %>% 
    group_by(ConditionA, ConditionA.1) %>% 
    nest %>%
    mutate(data = map(data, as.list)) %>%
    pull(data) 

2
也许可以使用 data.table 进行操作。
数据:
dat = data.frame (
  ConditionA = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
  ConditionB = c(1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5),
  X = c(460, 382, 468, 618, 421, 518, 655, 656, 621, 552, 750, 725, 337, 328, 342, 549, 569, 523, 469, 429),
  Y = c(437, 305, 498, 620, 381, 543, 214, 181, 183, 387, 439, 351, 327, 268, 276, 178, 375, 393, 312, 302)
)

代码:

library('data.table')
setDT(dat)
dat[, list(list(as.list(.SD))),by = .(ConditionA, ConditionB)][, V1]

或者这个

dat[, list(list(list(.SD))),by = .(ConditionA, ConditionB)][, V1]

2
c(by(dat[3:4],dat[1:2],as.list))
[[1]]
[[1]]$X
[1] 460 382 468 618

[[1]]$Y
[1] 437 305 498 620


[[2]]
[[2]]$X
[1] 421 518 655 656 621

[[2]]$Y
[1] 381 543 214 181 183


[[3]]
[[3]]$X
[1] 552 750 725

[[3]]$Y
[1] 387 439 351

 . . . . 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接