R 创建列的副本,其中新列偏移某个固定量
我正在寻找在数据框中创建现有列的副本,该列偏移了多行。
例如,如果column2 是column1 偏移1 的副本,那么
> dataframe
$column1
[1] 1 2 3 4 5
$column2
[1] 0 1 2 3 4
我通过以下代码取得了一些成功:
offset7 <- rep(0, 7)
dataframe$column1.prev7 = c(offset7, dataframe$column1[1:(length(dataframe$column1)-7)])
但是,如果我偏移30 或更多,它就会开始给出错误。我的数据足够长,不会出现偏移量大于行数的问题。错误是:
Error in dataframe$column1[1:(length(dataframe$column1) - 30)] :
only 0's may be mixed with negative subscripts
提前致谢!与 plyr 配合良好的快速循环免费版本将是首选。这里的目的是将时间序列数据分解为长达一年的各种滞后,然后以各种方式分析结果。
I'm looking to create a copy of an existing column in a dataframe that is offset by a number of rows.
E.g. if column2 is a copy of column1 offset by 1, then
> dataframe
$column1
[1] 1 2 3 4 5
$column2
[1] 0 1 2 3 4
I've had some success with the following code:
offset7 <- rep(0, 7)
dataframe$column1.prev7 = c(offset7, dataframe$column1[1:(length(dataframe$column1)-7)])
However it starts giving errors if I offset by 30 or more. My data is long enough for this not to be a problem of the offset being larger than the number of rows. The error is:
Error in dataframe$column1[1:(length(dataframe$column1) - 30)] :
only 0's may be mixed with negative subscripts
Thanks in advance! A fast loop free version that plays nice with plyr would be preferred. The intention here is to break up the timeseries data into various lags up to a year and then analyse the results in various ways.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请使用正确的时间序列类进行时间序列操作。最受欢迎的是 zoo 和 xts 两者都有大量文档。
作为一个简单的例子,考虑
但不要手工完成。并在此处搜索“[r] xts”或“[r] Zoo”以在 R 标签内进行搜索。
Please use a proper time-series class for time-series operations. Popular favourites are zoo and xts both of which have plenty of documentation.
As a simple example, consider
But just don't do it by hand. And do search here for '[r] xts' or [r] zoo' to search within the R tag.