简体   繁体   English

如何在R中使用内部变量

[英]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: 这是我的函数以及对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 : 应用了我的函数的data.frame的尺寸:

> dim(ind1)  
[1] 9 9

The problem is with div <- nrow(values). 问题在于div <-nrow(values)。 div = 9 is what I need here. div = 9是我在这里需要的。 So how to get nrow for my "values" inside function ? 那么,如何在函数内部获取“值”呢? Am I clear ? 我清楚吗?

Any help would be greatly appreciated ! 任何帮助将不胜感激 !

When you use apply() , you are running your function on every column of your data. 使用apply() ,将在数据的每一列上运行函数。 When the function is called by apply() , it is passed a vector representing a column. apply()调用该函数时,将传递代表列的向量。 So instead of nrow(values) , you should use length(values) . 因此,您应该使用length(values)而不是nrow(values) length(values)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM