[英]How do I use loops for automating work in R?
I have a file with data on the delivery of products to the store.I need to calculate the total number of products in the store.我有一个文件,其中包含有关向商店交付产品的数据。我需要计算商店中的产品总数。 I want to use the knowledge of cycles to calculate the total quantity of the product in the store, but my cycle only counts the total quantity of the last product.我想用周期的知识来计算店里产品的总量,但是我的周期只统计最后一个产品的总量。 Why?为什么? Here is the delivery data:以下是发货数据:
"Day" "Cott.cheese, pcs." "Kefir, pcs." "Sour cream, pcs."
1 104 117 119
2 94 114 114
3 105 107 117
4 99 112 120
5 86 104 111
6 88 110 126
7 95 106 129
I put this table in the in1 variable Here is code:我将此表放在in1变量中 这是代码:
s<-0
for (p in (2:ncol(in1))){
s<-sum(in1[,p]) }
s
Not sure I understand correctly your question but if you only want to add all values of your data.frame except for the first column (Day), you just need to do this:不确定我是否正确理解您的问题,但如果您只想添加除第一列(Day)之外的 data.frame 的所有值,您只需执行以下操作:
sum(in1[,-1])
You are rewriting the s variable each iteration, that's why it only shows the result for the last column.您每次迭代都在重写 s 变量,这就是为什么它只显示最后一列的结果。 Try尝试
s<-c()
for (p in 2:ncol(in1)) {
s<-c(s,sum(in1[,p]))
}
alternatively或者
colSums(in1[,-1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.