1

我有一个简单的数据框,我试图将其转换为列表列表,同时还将几列组合成每行的数字向量。例如,数据框如下所示:

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” “, ETC...

所需的输出看起来像这样(除了 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")))

我对拆分有点搞砸了,但它产生了一个数据帧列表,更重要的是我仍然无法找到一种方法来组合调用中的列。我是列表新手,所以可能有一些简单的方法可以做到这一点,我不知道。谢谢,

4

1 回答 1

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"
于 2013-10-31T18:27:36.420 回答