Echo
Echo

Reputation: 21

want one of the parameter to be a variable in my data when creating a function

My code is:

SMD.dicho <- function(data,c){
  a <- nrow(subset(data,c==1 & treat==1))
  b <- nrow(subset(data,c==0 & treat==1))
  c <- nrow(subset(data,c==1 & treat==0))
  d <- nrow(subset(data,c==0 & treat==0))
  pt <- a/(a+b)
  pc <- c/(c+d)
 return (pt-pc)/((pt*(1-pt)+pc*(1-pc))/2)^{0.5}
}

SMD.dicho(brain,sex)

brain is my dataset, c is one of the variables in my dataset, for example, a variable called sex in my dataset to indicate if this person is a man.however when I run my code, it shows

Error in factor(c): object 'sex' not found

Upvotes: 0

Views: 31

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

If you pass unquoted variable to the function, it would require non-standard evaluation which might complicate things and can be confusing in the beginning. Without changing much of your current approach, pass the column name as character and get the counts.

SMD.dicho <- function(data, col) {
   a <- sum(data[[col]] == 1 & data[["treat"]] == 1)
   b <- sum(data[[col]] == 0 & data[["treat"]] == 1)
   c <- sum(data[[col]] == 1 & data[["treat"]] == 0)
   d <- sum(data[[col]] == 0 & data[["treat"]] == 0)
   pt <- a/(a+b)
   pc <- c/(c+d)
   return (pt-pc)/((pt*(1-pt)+pc*(1-pc))/2)^{0.5}
}

SMD.dicho(brain,"sex")

Upvotes: 2

Related Questions