1

I have created a code to obtain statistics on a variable and I would like to automate it in a function to use it on other variables.

Name of the dataframe: data Name of the variable: UNIQUE

Code:

  table1 <- table(data$UNIQUE, useNA = "ifany", dnn = "Variables")
  dataframe1 <- as.data.frame(table1, row.names = NULL, responseName = "N")
  dataframe1$N <- as.numeric(dataframe1$N)

Now I'm trying to do the function using the table and the variable in arguments like:

function1 <- function(Table, Variable){
    table1 <- table(Table$Variable, useNA = "ifany", dnn = "Variables")
    dataframe1 <- as.data.frame(table1, row.names = NULL, responseName = "N")
    dataframe1$N <- as.numeric(dataframe1$N)
    dataframe1
}

I tried with the assign and paste functions but I couldn't find the solution.

Thanks by advance, Pierre

joran
  • 169,992
  • 32
  • 429
  • 468
RStudio35
  • 11
  • 1
  • 2
  • 1
    You need to replace `Table$Variable` with `Table[,Variable]`. When you pass `Variable` into your function it is as an object of type `character`. Subsetting with `$` requires a bare variable name, whereas square bracket notation will accept `character` objects. – divibisan Oct 19 '18 at 14:46
  • Pass a character to `Variable` and stop using `$`, instead use `Table[[Variable]]`. `$` is for interactive use, `[[` is for programming. – joran Oct 19 '18 at 14:46
  • that's how I do `set_symb=as.symbol(variable); use <- eval(set_symb,Table);` then use use (parsing variable as text) – R. Prost Oct 19 '18 at 14:49

0 Answers0