2

我有一个由不同长度的不同数字向量组成的列表,我想知道您是否对如何提取具有相同索引的对象有任何建议(例如,每个元素的第三个对象)

想象一下我有这样的事情:

States<-list(Italy=rbinom(5,4,0.5),Spain=rnorm(12,6,1),Greece=sample(1:14, 6))
> States
$Italy
[1] 2 2 1 4 2

$Spain
 [1] 5.403135 5.616146 7.224063 5.602878 6.738619 6.732706 7.636093 5.917246 5.901094
[10] 5.818594 7.420575 5.545782

$Greece
[1]  8  9  3 11  4 14

如何获得一个数字向量,其中每个元素的第一个对象是一个向量,例如:

[1] 2 5.403135 8

谢谢!

4

1 回答 1

1

Consider using lapply or sapply, which will both eventually get you to the same result:

For lapply:

> lapply(States,function(x)x[1])
$Italy
[1] 2

$Spain
[1] 6.694136

$Greece
[1] 10
> unlist(lapply(States,function(x)x[1]), use.names=FALSE)
[1]  2.000000  6.694136 10.000000

For sapply:

> sapply(States,function(x)x[1])
    Italy     Spain    Greece 
 2.000000  6.694136 10.000000
> as.vector(sapply(States,function(x)x[1]))
[1]  2.000000  6.694136 10.000000
于 2013-07-03T20:54:21.203 回答