从R中的列表中获取元素内的元素

时间:2018-08-20 03:07:16

标签: arrays r lapply

我想使用lapply函数从列表中提取嵌入在元素内的元素。原始列表包含碰巧是数组的元素,R包geomorph中的gpagen函数弹出一个新列表,其中每个元素都包含一个嵌入其中的元素,我想将这些嵌入的元素定向到一个新对象。 / p>

输入示例:

>unaligned_coords
$individual1
, , rep1

         [,1]      [,2]     [,3]
[1,] 58.81923  2.452332 273.2005
[2,] 68.24838 -4.298481 271.2884
[3,] 69.58006 -1.127088 270.0316

, , rep2

         [,1]      [,2]     [,3]
[1,] 58.82360  2.485687 273.1929
[2,] 68.14501 -4.233420 271.3564
[3,] 69.02335 -0.875766 270.4671

$individual2
, , rep1

         [,1]       [,2]     [,3]
[1,] 58.64723 -1.7827113 271.4866
[2,] 69.53938 -7.0807052 274.4347
[3,] 72.35068  0.1114307 272.1112

, , rep2

         [,1]       [,2]     [,3]
[1,] 58.63091 -1.7735939 271.4576
[2,] 68.78160 -6.9430161 274.1252
[3,] 73.07706  0.3313497 272.1727

...

在输入示例中使用lapply:

aligned_coords <- lapply(unaligned_coords, gpagen)

输出,其中元素(坐标)嵌入元素(个体)中:

>aligned_coords$individual1$coords
, , rep1

           [,1]         [,2]         [,3]
[1,] -0.1838745 -0.002361134  0.001343360
[2,]  0.1717784 -0.065992358 -0.003245113
[3,]  0.1701612  0.025533125 -0.068783434

, , rep2

           [,1]        [,2]          [,3]
[1,] -0.1844239  0.00147890  0.0001282347
[2,]  0.1846240 -0.07485290 -0.0031490047
[3,]  0.1681969  0.02331805 -0.0627923402

>aligned_coords$individual2$coords
, , rep1

           [,1]         [,2]        [,3]
[1,] -0.1439503  0.007217439  0.04066458
[2,]  0.1154014 -0.009312094 -0.10422833
[3,]  0.1673553  0.117909836  0.03056590

, , rep2

            [,1]         [,2]        [,3]
[1,] -0.14248417  0.004972831  0.03475940
[2,]  0.09739824 -0.008022416 -0.09583761
[3,]  0.17839128  0.122139269  0.03668812

所需的输出示例:

>aligned_coords
$individual1
 , , rep1

            [,1]         [,2]         [,3]
 [1,] -0.1838745 -0.002361134  0.001343360
 [2,]  0.1717784 -0.065992358 -0.003245113
 [3,]  0.1701612  0.025533125 -0.068783434

 , , rep2

            [,1]        [,2]          [,3]
 [1,] -0.1844239  0.00147890  0.0001282347
 [2,]  0.1846240 -0.07485290 -0.0031490047
 [3,]  0.1681969  0.02331805 -0.0627923402

$individual2
 , , rep1

            [,1]         [,2]        [,3]
 [1,] -0.1439503  0.007217439  0.04066458
 [2,]  0.1154014 -0.009312094 -0.10422833
 [3,]  0.1673553  0.117909836  0.03056590

 , , rep2

             [,1]         [,2]        [,3]
 [1,] -0.14248417  0.004972831  0.03475940
 [2,]  0.09739824 -0.008022416 -0.09583761
 [3,]  0.17839128  0.122139269  0.03668812

...

lapply可能吗?我尝试了以下方法:

aligned_coords <- lapply(unaligned_coords, gpagen)$coords

但是我得到了

>aligned_coords
NULL

1 个答案:

答案 0 :(得分:0)

在应用coords函数之后,我们可以使用匿名函数调用提取gpagen

library(geomorph)
lapply(unaligned_coords, function(x) gpagen(x)$coords)

数据

set.seed(24)
unaligned_coords <- list(individual1 = array(rnorm(3 * 3 * 2, 60), 
  dim = c(3, 3, 2), dimnames = list(NULL, NULL, c("rep1", "rep2"))), 
 individual2 = array(rnorm(3 * 3 * 2, 60), dim = c(3, 3, 2), 
   dimnames = list(NULL, NULL, c("rep1", "rep2")) ) )