循环选择成对系列
我在 R 中有一个包含 40 系列的 data.frame,我想选择成对系列来应用函数(即 serie 1 和 serie 21、serie 2 和 serie 22)。但是,我在以下代码中遇到错误:
for(i in 1:ncol(Date)) {
pairwise <-Date[, c(i,i+20)]
}
我想在其他函数中使用 pairwise
。
有人可以帮我吗?
提前致谢
I have a data.frame
in R with 40 series and I want to select pairwise series to apply a function, (ie serie 1 and serie 21, serie 2 and serie 22) . However I'm getting error with the following code:
for(i in 1:ncol(Date)) {
pairwise <-Date[, c(i,i+20)]
}
I want to use pairwise
in other function.
Could someone please help me?
Thank in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为当
i
> 时,您请求的列数高于 40。 20. 看这个例子:你得到这个错误:
那是因为
i
取值 1, ..., 40。 一旦 i >= 21,(i + 20) > 40 并且您只有 40 列数据。一个简单的修改是仅循环前 20 列:如果您想要的只是 col 1 和 col 21、col 2 和 col 22 等。如果您想要所有成对比较,那么您需要尝试不同的方法,因为单个循环会获胜不工作。
(在有人因为循环使用效率低下而指责我之前,那个例子只是一个没有想象力应用于函数
foo()
的例子。在这种情况下,DF[, 1:20] - DF[, 21:40]
将给出与res
中相同的结果。)It is because you are requesting columns higher than 40 when
i
> 20. See this example:You get this error:
That is because
i
takes values 1, ..., 40. As soon as i >= 21, (i + 20) > 40 and you only have 40 columns of data. A simple modification is to loop only over the first 20 columns:if all you want is col 1 and col 21, col 2 and col 22 etc. If you want all pairwise comparisons then you need to try something different, as a single loop won't work.
(Before someone pulls me up for woefully inefficient use of a loop, that example was just that, an example with no imagination applied to the function
foo()
. In this case,DF[, 1:20] - DF[, 21:40]
will give the same result as inres
.)