我想像这样转变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
. . .
进行此类转换的最有效方法是什么?
答案 0 :(得分:3)
我们可以根据第1列和第2列执行split
,使用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)
答案 1 :(得分: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 :(得分: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
. . . .