简体   繁体   中英

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:

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:

sum(in1[,-1])

You are rewriting the s variable each iteration, that's why it only shows the result for the last column. Try

s<-c()
for (p in 2:ncol(in1)) {
  s<-c(s,sum(in1[,p]))
}

alternatively

colSums(in1[,-1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM