[R] write a loop for tallies

Erik Iverson eriki at ccbr.umn.edu
Fri Jun 25 01:13:36 CEST 2010


On average, any data manipulation that can be described in a sentence or two of 
English can be programmed in one line in R. If you find yourself writing a long 
'for' loop to do something that sounds simple, take a step back and research if 
an existing combination of functions can easily handle your request.

john polo wrote:
> Dear R users,
> 
> I have a list of numbers such as
> 
>  > n
> [1] 3000 4000 5000 3000 5000 6000 4000 5000 7000 5000 6000 7000
> 
> and i'd like to set up a loop that will keep track of the number of 
> occurences of each of the values that occur in the list, e.g.
> 
> 3000: 2
> 4000: 2
> 5000: 4
> 
> I came up with the following:
> 
> a<- for (i in 1:length(n)) {
> r<-0
> s<-0
> t<-0
> u<-0
> v<-0
> ifelse(n[i] == "3000", r <- r+1,
> ifelse(n[i] == "4000", s <- r+1,
> ifelse(n[i] == "5000", t <- r+1,
> ifelse(n[i] == "6000", u <- r+1,
> ifelse(n[i] == "7000", v <- r+1, NA)))))
> r<-sum(r)
> s<-sum(s)
> t<-sum(t)
> u<-sum(u)
> v<-sum(v)
> cat("r = ", r, "\n")
> cat("s = ", s, "\n")
> cat("t = ", t, "\n")
> cat("u = ", u, "\n")
> cat("v = ", v, "\n")
> }
> 
> However, this is the output:
> 
> r =  1
> s =  0
> t =  0
> u =  0
> v =  0
> r =  0
> s =  1
> t =  0
> u =  0
> v =  0
> r =  0
> s =  0
> t =  1
> u =  0
> v =  0
> r =  1
> s =  0
> t =  0
> u =  0
> v =  0
> r =  0
> s =  0
> t =  1
> u =  0
> v =  0
> r =  0
> s =  0
> t =  0
> u =  1
> v =  0
> r =  0
> s =  1
> t =  0
> u =  0
> v =  0
> r =  0
> s =  0
> t =  1
> u =  0
> v =  0
> r =  0
> s =  0
> t =  0
> u =  0
> v =  1
> r =  0
> s =  0
> t =  1
> u =  0
> v =  0
> r =  0
> s =  0
> t =  0
> u =  1
> v =  0
> r =  0
> s =  0
> t =  0
> u =  0
> v =  1
> 
> How should i write this loop, please? I've tried variations with "if" 
> instead of "ifelse" and receive errors about "unexpected {" or 
> "unexpected )".
> 
> regards,
> john
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list