Reputation: 1306
So write now I'm writing a function in R that looks at a set of vectors presented as a matrix, and two test vectors, and then checks each vector in the original set, and decides which of the two test vectors it's closer to (or neither), and then out puts the three datasets as matrices (the vectors closer to the first test, second test, and neither). I wrote another function which just looks at three vectors, and then gives as an output which vector the first vector is closer to (that's the closer function). It, and its results, are used in the new function.
Here is the code for the bigger function:
vectorwork <- function(mat,test1,test2){
closer1 = ()
closer2 = ()
neither = ()
y = dim(mat)[2]
for(i in 1:(dim(mat)[1]){
if(closer(mat[i,],test1,test2)==1){
closer1[length(closer1)+1] = mat[i,]
}
else if(closer(mat[i,],test1,test2)==2){
closer2[length(closer2)+1] = mat[i,]
}
else{
neither[length(neither)+1] = mat[i,]
}
}
close1 = matrix(closer1, (length(closer1)/y), y)
close2 = matrix(closer2, (length(closer2)/y), y)
neith = matrix(neither, (length(neither)/y), y)
print(close1,close2,neith)
}
I keep getting paren errors all over the code. Since I'm new to R, I'm not really sure where exactly I'm going wrong. Any help would be appreciated!
Upvotes: 0
Views: 120
Reputation: 8272
Your problem is unbalanced parentheses.
for(i in 1:(dim(mat)[1]) {
^ ^ C C ^ <--- innermost pair
| B B <- middle pair
A <- outermost one is unpaired
This is basic. Count!
for(i in 1:(dim(mat)[1]) ) {
^
|
put it in
The thing is, from your post ("paren errors") and comments ("Error: unexpected '{' in: " for(i in 1:(dim(mat)[1]) {"), it looks like you apparently already knew what the problem was AND you apparently already knew what line the problem was on. Given that, all you needed to do was count to three.
Here's a little trick I use when checking parentheses; as I read across, I count "1", "2" as I hit each "(". Then when I hit a ")" I subtract again, going up and down as I hit more "(" and ")". By the time I get to where it all should be closed off, I better hit 0.
Consider your offending line. The count has to hit zero before the "{" ! Does it?
for(i in 1:(dim(mat)[1]) {
1 2 3 2 1 Nope. I'm short a ")".
This doesn't usually find the exact place to insert the missing one, but it quickly shows you definitely have a problem and then it's usually easy to find.
Upvotes: 0
Reputation: 179558
One of the fundamentals of R is that it makes use of vectors. This means you can do an element-by-element comparison of two vectors with a simple ==
comparison:
x==a
So, try this instead:
set.seed(1)
x <- sample(1:5, 10, replace=TRUE)
a <- sample(1:5, 10, replace=TRUE)
b <- sample(1:5, 10, replace=TRUE)
sum(x==a)
[1] 1
sum(x==b)
[1] 2
To get your last comparison, put a logical AND operator &
in the evaluation:
sum(x!=a & x!=b)
[1] 7
Upvotes: 4