What's the right way to do in R:
for(row in 1:10)
{
counts[row] <- length(otherData[otherData[["some property"]] == otherList[row],])
}
In other words, put into each row of a new anything (matrix, data.frame, whatever) the count of those rows in another anything (matrix, data.frame, whatever) that equal the corresponding entry in some other list (again abstractly speaking, not literally list object)?
E.g. say x = otherData is
a b c
d 1 2 3
e 1 3 4
f 2 5 6
g 1 5 3
And say the "otherList" is the first column of x, so I want to count how many of x's rows have each of 1, 2, 3, etc. first
So I want counts to be
3,
1,
0,
(0s as long as this counts list goes)
Note it's more important that I be able to select out that data subset than that I get its length; I need to use the subset for other computations as well, though again want to select it out row-by-row and have the output of whatever computations I do stored in the row of the results (in this case counts) matrix.
I can obviously do this with a for loop, but what's the clever way to skip the loop?
Apologies if this duplicates another question. This seems like a very basic question, but I'm not sure what terms to search for. This question seems similar and would work for getting lengths, though I'm not clear on how to apply it in the general case.
EDIT
Here's an example. We select certain rows of x (here x is like otherData in my description above) that satisfy some row-dependent condition, in this case having a first col entry = to row, but the point is that "== row" could be replaced with any condition on row, e.g. "<= otherlist[row]-2" etc.
> x
condition value
1 2 25
2 9 72
3 41 60
4 41 61
5 25 38
6 41 10
7 41 43
8 41 26
9 41 46
10 12 263
11 26 136
12 24 107
13 9 70
14 12 62
15 12 136
16 34 44
17 12 53
18 32 14
19 32 148
20 4 34
> results = 0*1:20
> results
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
> for(row in 1:20) {
+ results[row] = length(x[x[["condition"]]==row,2]) }
> results
[1] 0 1 0 1 0 0 0 0 2 0 0 4 0 0 0 0 0 0 0 0