[R] write a loop for tallies
john polo
jpolo at mail.usf.edu
Fri Jun 25 00:16:21 CEST 2010
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
More information about the R-help
mailing list