R:为什么我的向量是无序的? [英] R: Why my vector is disordered?
问题描述
假设我有这个动物园矢量
Let say I have this zoo vector
mine <- zoo(c(rep(0,4),rep(1,4),rep(0,5),rep(1,23),rep(0,4),rep(1,2)),as.chron(seq(1:42)))
我想按某种顺序提取几个元素
And I want to extract several elements in some order
> mine[14]
01/15/70
1
> mine[5]
01/06/70
1
> mine[41]
02/11/70
1
它有效!.但现在我尝试以不同的方式来做
It works!. But now I try to do it in a different way
zz <- c(14, 5, 41)
mine[zz]
01/06/70 01/15/70 02/11/70
1 1 1
我不知道为什么我以不同的顺序得到它.我怎样才能保持我想要的顺序,我的列表的顺序??我不介意它是一个列表、一个向量、按列还是按行,但我想按照我要求的顺序来获取它.
I don't know why I get it in a different order. How can I keep the order I want, the order of my list ?? I don't mind if it's a list, a vector, by columns or by row, but I'd like to get it in the order I've asked for.
干杯
推荐答案
zoo 这样做的原因是它有一个函数 [
([.zoo
),并从子集值创建一个新的 zoo 对象,它在逻辑上希望重新排序,以便它是一个有效的 zoo 对象.
The answer to why zoo does this is that it has a method for the function [
([.zoo
), and it creates a new zoo object from the subsetted values, which it logically wants to reorder so that it is a valid zoo object.
您可以通过相关访问器函数访问时间索引和数据来实现您想要的:
You can achieve what you want by accessing the time indices and data via the relevant accessor functions:
> index(mine)[c(14, 5, 41)]
[1] 01/15/70 01/06/70 02/11/70
> coredata(mine)[c(14, 5, 41)]
[1] 1 1 1
如果您想将其合并为一个步骤,请编写您自己的乐趣:
If you want to combine this into a single step, write your own fun to do:
myExtract <- function(x, want) {
out <- coredata(mine)[want]
names(out) <- index(x)[want]
out
}
给出:
> myExtract(mine, want = c(14, 5, 41))
01/15/70 01/06/70 02/11/70
1 1 1
这篇关于R:为什么我的向量是无序的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!