考虑以下情况,我在对象中有一个n矩阵列表(这只是下面例子中的虚拟数据) myList
mat <- matrix(1:12, ncol = 3)
myList <- list(mat1 = mat, mat2 = mat, mat3 = mat, mat4 = mat)
我想从每个矩阵中选择一个特定的列并用它做一些事情.这将获得每个矩阵的第一列并将其作为矩阵返回(lapply()给我一个列表也可以).
sapply(myList, function(x) x[, 1])
我似乎无法做的是[直接用作我sapply()或lapply()咒语中的函数.?'['告诉我,我需要提供参数j作为列标识符.那么我做错了什么,这不起作用?
> lapply(myList, `[`, j = 1)
$mat1
[1] 1
$mat2
[1] 1
$mat3
[1] 1
$mat4
[1] 1
在哪里我会期望这个:
$mat1
[1] 1 2 3 4
$mat2
[1] 1 2 3 4
$mat3
[1] 1 2 3 4
$mat4
[1] 1 2 3 4
我怀疑我的[方法不对,但我找不到原因?思考?
fra*_*nkc 24
我认为你得到了1的论证形式[.如果你这样做的lapply(myList, `[`, i =, j = 1)话.
Rei*_*son 14
经过两品脱英国最好的啤酒和一点点的思考之后,我意识到这个版本会起作用:
lapply(myList, `[`, , 1)
即不要说出任何东西,并像我一样对待它mat[ ,1].仍然不要grep为什么命名j不起作用...
......实际上,?'['仔细阅读后,我注意到以下部分:
Argument matching:
     Note that these operations do not match their index arguments in
     the standard way: argument names are ignored and positional
     matching only is used.  So ‘m[j=2,i=1]’ is equivalent to ‘m[2,1]’
     and *not* to ‘m[1,2]’.
这解释了我上面的窘境.是的,实际上阅读文档.
| 归档时间: | 
 | 
| 查看次数: | 4402 次 | 
| 最近记录: |