r - 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)
解决方案
正如评论中提到的,你的工作在应该如何做方面看起来不太合乎逻辑......无论如何,如果我正确理解你的问题,可能的解决方案是:
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)
推荐阅读
- mysql - 为什么续集插入两次?
- amazon-s3 - 使用 IAM 用户的预签名 URL - 拒绝访问
- java - 在java中导入相同命名的包
- javascript - 如何将值从 Node 发送到 HTML 以在 JavaScript 中处理?
- javascript - 水平滚动事件未在 Windows 上触发
- python - 单位置索引器在 while 循环 pandas 上越界
- css - 导入散列 CSS className 并在另一个文件中选择它
- python - Flask-sqlalchemy 'Models_committed' 没有调用通过装饰器注册的函数
- c - 如何正确归一化 q15 定点中的 pid 系数
- azure - 将 Xamarin 和 Azure B2C 与 MSAL 结合使用