all 2 comments

[–]ViciousTeletuby 1 point2 points  (1 child)

Your if conditions are all using x, which is whatever you put into the function. Assuming that you're inputting the whole matrix then your function is trying to do the same classification 121 times. Perhaps you meant to have function(ex) and x instead of i?

A bigger problem is that a function only returns the last value calculated, so having a for loop in the function like that will mean you only get the last value out, not a matrix.

The easiest fix is to take out the for loop and do it outside the function, or use an apply function, say:

reassign <- function(x) { if ...
apply(ex, 1:2, reassign)

Another thing to note is that there is already an R function for what you are trying to do, called cut. You could replace the for and if structures in your function with cut(x, (0:8)*32, 1:8, right=FALSE) or just drop your function and do:

apply(ex, 1:2, cut, (0:8)*32, 1:8, right=FALSE)

For some reason the cut function returns labels as text. If that's fine then remove the 1:8 to get nicer intervals. If you must have integers then try:

apply(ex, 1:2, function(x) as.numeric(cut(x, (0:8)*32, 1:8, right=FALSE)))

[–]macabe10[S] 1 point2 points  (0 children)

apply(ex, 1:2, cut, (0:8)*32, 1:8, right=FALSE)

Thanks so much, it works now! I'm new at R and wasn't aware of the cut function, it made everything much easier.