避免R中的循环 [英] Avoiding loops in R
问题描述
我决定学习R.我试图了解如何编写"R风格"函数,并避免循环.这是一个示例情况:
I have decided to learn R. I am trying to get a sense of how to write "R style" functions and to avoid looping. Here is a sample situation:
给定一个向量a
,我想计算一个向量b
,其元素b[i]
(向量索引从1开始)定义如下:
Given a vector a
, I would like to compute a vector b
whose elements b[i]
(the vector index begins at 1) are defined as follows:
1 <= i <= 4:
b[i] = NaN
5 <= i <= length(a):
b[i] = mean(a[i-4] to a[i])
基本上,如果我们假装"a"是一个速度列表,其中第一个条目在时间= 0,第二个条目在时间= 1秒,第三个条目在时间= 2秒...我想获得一个表示过去5秒内平均速度的相应向量.
Essentially, if we pretend 'a' is a list of speeds where the first entry is at time = 0, the second at time = 1 second, the third at time = 2 seconds... I would like to obtain a corresponding vector describing the average speed over the past 5 seconds.
例如:
如果a is (1,1,1,1,1,4,6,3,6,8,9)
,则b
应该是(NaN, NaN, NaN, NaN, 1, 1.6, 2.6, 3, 4, 5.4, 6.4)
E.g.:
If a is (1,1,1,1,1,4,6,3,6,8,9)
then b
should be (NaN, NaN, NaN, NaN, 1, 1.6, 2.6, 3, 4, 5.4, 6.4)
我可以使用循环来执行此操作,但是我觉得这样做不是"R风格".
I could do this using a loop, but I feel that doing so would not be in "R style".
谢谢
Tungata
推荐答案
由于这些滚动功能通常适用于时间序列数据,因此一些更新和更丰富的时间序列数据处理软件包已经为您做到了:>
Because these rolling functions often apply with time-series data, some of the newer and richer time-series data-handling packages already do that for you:
R> library(zoo) ## load zoo
R> speed <- c(1,1,1,1,1,4,6,3,6,8,9)
R> zsp <- zoo( speed, order.by=1:length(speed) ) ## creates a zoo object
R> rollmean(zsp, 5) ## default use
3 4 5 6 7 8 9
1.0 1.6 2.6 3.0 4.0 5.4 6.4
R> rollmean(zsp, 5, na.pad=TRUE, align="right") ## with padding and aligned
1 2 3 4 5 6 7 8 9 10 11
NA NA NA NA 1.0 1.6 2.6 3.0 4.0 5.4 6.4
R>
zoo 具有出色的文档,它将向您展示更多示例,特别是如何使用真实(可能是不规则)日期执行此操作; xts 对此进行了进一步扩展,但
The zoo has excellent documentation that will show you many, many more examples, in particular how to do this with real (and possibly irregular) dates; xts extends this further but zoo is a better starting point.
这篇关于避免R中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!