Reputation: 129
with a dataset, one column is "1, 1, 1, ... 2, 2, 2, .. 3, 3, 3, 3 ..." with varying amounts of the same number repeated. I want to find the total of all the 1s, all the 2s and so forth... How can I do that with a for loop? How can I tell when the number in that column changes?
This is what I'm thinking:
for (i in 1: length(data)) {
for (j in [beginning of first] to [end of first]) {
#do something
}
}
But how do I find the beginning of first and end of first? Thank you
Upvotes: 0
Views: 47
Reputation: 51640
As a note of general advice, if you are using R and start thinking of using a for
loop, you should see whether there is a better way to do that.
For instance, to solve your problem you just need to do:
table(data$columnName)
So, for instance
> set.seed(12345) # set seed, for reproducibility
> myvar <- rep(1:10, sample(1:20,10,rep=T)) # Generate some data
> myvar
[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2
[26] 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4
[51] 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5
[76] 5 5 6 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 9
[101] 9 9 9 9 9 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10 10
[126] 10 10 10 10 10 10 10 10 10
> table(myvar)
myvar
1 2 3 4 5 6 7 8 9 10
15 18 16 18 10 4 7 11 15 20
Upvotes: 1