循环选择成对系列

发布于 2024-10-08 19:17:02 字数 269 浏览 0 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巴黎夜雨 2024-10-15 19:17:02

这是因为当 i > 时,您请求的列数高于 40。 20. 看这个例子:

set.seed(1)
DF <- data.frame(matrix(rnorm(40*100), ncol = 40))

## simple function to apply/use
foo <- function(x1, x2) return(x1 - x2)

## something to hold results
res <- matrix(ncol = ncol(DF), nrow = nrow(DF))

## loop - oops error
for(i in seq_len(ncol(DF))) {
    res[,i] <- foo(DF[,i], DF[,i+20])
}

你得到这个错误:

Error in `[.data.frame`(DF, , i + 20) : undefined columns selected

那是因为 i 取值 1, ..., 40。 一旦 i >= 21,(i + 20) > 40 并且您只有 40 列数据。一个简单的修改是仅循环前 20 列:

## something to hold results
res <- matrix(ncol = ncol(DF) / 2, nrow = nrow(DF))
for(i in seq_len(ncol(DF)/2)) {
    res[,i] <- foo(DF[,i], DF[,i+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:

set.seed(1)
DF <- data.frame(matrix(rnorm(40*100), ncol = 40))

## simple function to apply/use
foo <- function(x1, x2) return(x1 - x2)

## something to hold results
res <- matrix(ncol = ncol(DF), nrow = nrow(DF))

## loop - oops error
for(i in seq_len(ncol(DF))) {
    res[,i] <- foo(DF[,i], DF[,i+20])
}

You get this error:

Error in `[.data.frame`(DF, , i + 20) : undefined columns selected

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:

## something to hold results
res <- matrix(ncol = ncol(DF) / 2, nrow = nrow(DF))
for(i in seq_len(ncol(DF)/2)) {
    res[,i] <- foo(DF[,i], DF[,i+20])
}

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 in res.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文