0

I'd like to use a variable in my function but I can't figure out how to do this. Here is my function and the call on a data.frame:

errorByAleles <- function(values){
  counts1 <- as.data.frame(table(values), stringsAsFactors = FALSE)
  modal_value1 <- which.max(counts1$Freq)
  div <- nrow(values)
  return ((sum(counts1$Freq)-counts1$Freq[modal_value1])/div)
}

error1 <- apply(X=ind1[,2:9],MARGIN=2,FUN=errorByAleles)

Dimmension of data.frame on which I apply my function :

> dim(ind1)  
[1] 9 9

The problem is with div <- nrow(values). div = 9 is what I need here. So how to get nrow for my "values" inside function ? Am I clear ?

Any help would be greatly appreciated !

8
  • You can't do that with the function as written because div is only defined within the scope of your function. You'll need to either change the function or calculate the value of div separately outside of the function. Commented Feb 18, 2012 at 1:45
  • Mmmmm, I guess I'll have to change my function, as div is variable... Commented Feb 18, 2012 at 1:54
  • MARGIN=2 requires an array of at least two dimensions, but ind1[2:9] is a vector, maybe you meant to do ind1[2:9, ] or ind1[, 2:9] ? Commented Feb 18, 2012 at 1:58
  • Question - since ind1 has dim 9x9, why does ind1[2:9] not throw an error when you call apply? That shouldn't work, are you missing a comma somewhere, like ind1[2:9,] or ind1[,2:9]? Commented Feb 18, 2012 at 1:59
  • @flodel Yes, thanks for pointing this out, I meant [,2:9]. Doesn't solve my problem though... Commented Feb 18, 2012 at 2:02

1 Answer 1

1

When you use apply(), you are running your function on every column of your data. When the function is called by apply(), it is passed a vector representing a column. So instead of nrow(values), you should use length(values).

Sign up to request clarification or add additional context in comments.

1 Comment

That's what I tried first, but length(values) gives me 1 inside the function.....

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.