我有一个简单的数据框,我试图转换为列表列表,同时还将几个列组合成每行的数字向量。例如,数据框如下所示:
Site c1 c2 c3
MUT -3.71 1.93 0.26
MBT -2.82 2.52 0.58
MFW -1.67 1.60 -0.09
可重现:
regression <- structure(list(site = structure(1:3, .Label = c("MUT", "MBT",
"MFW", "EUT", "EFW", "EBT", "PBT", "PUT", "PFW"), class = "factor"),
c1 = c(-3.71, -2.82, -1.67), c2 = c(1.93, 2.52, 1.6), c3 = c(0.26,
0.58, -0.09)), .Names = c("site", "c1", "c2", "c3"), row.names = c(NA,
3L), class = "data.frame")
我想从每一行中列出一个列表,将列“c1”,“c2”和“c3”组合成一个名为“params”的数字向量,其中每个值都名为“c1” ,“c2”等...
所需的输出看起来像这样(不知道除了dput之外如何清晰地写出它)
desired <- list(structure(list(name = "MUT", params = structure(c(-3.71,
1.93, 0.26), .Names = c("c1", "c2", "c3"))), .Names = c("name",
"params")), structure(list(name = "MBT", params = structure(c(-2.82,
2.52, 0.58), .Names = c("c1", "c2", "c3"))), .Names = c("name",
"params")), structure(list(name = "MFW", params = structure(c(-1.67,
1.6, -0.09), .Names = c("c1", "c2", "c3"))), .Names = c("name",
"params")))
我用分裂搞砸了一下,但它产生了一个数据帧列表,更重要的是我仍然无法找到一种方法来组合调用中的列。我是列表的新手,所以可能有一些简单的方法可以做到这一点,我不知道。 谢谢,
答案 0 :(得分:2)
您的问题并不完全清楚,但以下听起来就像您可能正在寻找的那样:
> lapply(split(regression[-1], seq_len(nrow(regression))), unlist)
$`1`
c1 c2 c3
-3.71 1.93 0.26
$`2`
c1 c2 c3
-2.82 2.52 0.58
$`3`
c1 c2 c3
-1.67 1.60 -0.09
> str(lapply(split(regression[-1], seq_len(nrow(regression))), unlist))
List of 3
$ 1: Named num [1:3] -3.71 1.93 0.26
..- attr(*, "names")= chr [1:3] "c1" "c2" "c3"
$ 2: Named num [1:3] -2.82 2.52 0.58
..- attr(*, "names")= chr [1:3] "c1" "c2" "c3"
$ 3: Named num [1:3] -1.67 1.6 -0.09
..- attr(*, "names")= chr [1:3] "c1" "c2" "c3"
现在您已经发布了一些示例输出,稍有不同:
out <- lapply(split(regression, seq_len(nrow(regression))),
function(x) list(name = as.character(x[[1]]),
params = unlist(x[-1])))
str(out)
# List of 3
# $ 1:List of 2
# ..$ name : chr "MUT"
# ..$ params: Named num [1:3] -3.71 1.93 0.26
# .. ..- attr(*, "names")= chr [1:3] "c1" "c2" "c3"
# $ 2:List of 2
# ..$ name : chr "MBT"
# ..$ params: Named num [1:3] -2.82 2.52 0.58
# .. ..- attr(*, "names")= chr [1:3] "c1" "c2" "c3"
# $ 3:List of 2
# ..$ name : chr "MFW"
# ..$ params: Named num [1:3] -1.67 1.6 -0.09
# .. ..- attr(*, "names")= chr [1:3] "c1" "c2" "c3"