Chargaff
Chargaff

Reputation: 1572

How to use a variable inside function in R

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 !

Upvotes: 0

Views: 368

Answers (1)

flodel
flodel

Reputation: 89097

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).

Upvotes: 1

Related Questions