首页 > 解决方案 > R循环没有循环正确的次数

问题描述

我的 DF 包含 9 列,3 组 3。在我尝试制作的总行中,我对第一列求和,对第二列求和,然后在第三列中除。重复第二组并重复第三组。除了我的循环不工作。它正在计算正确的集合数,3,但只循环两次。我的结果总计前 6 列/前 2 组。

df <- data.frame(a=c(200,200,200),b=c(20,20,20),c=c(10,10,10),d=c(100,100,100),e=c(2,2,2),f=c(50,50,50),g=c(200,200,200),h=c(20,20,20),i=c(10,10,10))

i <- 1
totals <- vector()

for (sets in (range(1:length(df))/3)){
  x <- colSums(df[i:i], na.rm = TRUE)
  i <- i + 1
  y <- colSums(df[i:i], na.rm = TRUE)
  i <- i + 1
  z <- x/y
  i <- i + 1
  totals <- c(totals,x,y,z)
}

totals <- c(0,totals)
print(totals)

标签: r

解决方案


正如评论中提到的,你的工作在应该如何做方面看起来不太合乎逻辑......无论如何,如果我正确理解你的问题,可能的解决方案是:

df <- data.frame(a=c(200,200,200),b=c(20,20,20),c=c(10,10,10),d=c(100,100,100),e=c(2,2,2),f=c(50,50,50),g=c(200,200,200),h=c(20,20,20),i=c(10,10,10))


i <- 1
totals <- vector()

for (sets in 1:nrow(df)){
   x <- colSums(df[i:i], na.rm = TRUE)
   i <- i + 1
   y <- colSums(df[i:i], na.rm = TRUE)
   i <- i + 1
   z <- x/y
   i <- i + 1
   totals <- c(totals,x,y,z)
}

totals <- c(0,totals)
print(totals)

推荐阅读