Search code examples
rfunctiondataframefrequency

Why is this R function that returns the frequency of a data frame value not working?


I am trying to do a function with two parameters (variable, value). The function returns the frequency of a data frame value. I've written the following code but it returns an error: object "variable" not found. Any ideas of why? Doing it step by step in the console seems to be working but not within the function.

data <- data.frame(SEX = c("MASCULINO", "FEMENINO", "FEMENINO","FEMENINO",
                          "MASCULINO", "FEMENINO", "FEMENINO","FEMENINO",
                          "MASCULINO", "FEMENINO", "FEMENINO","FEMENINO",
                          "MASCULINO", "FEMENINO", "FEMENINO","FEMENINO",
                          "MASCULINO", "FEMENINO", "FEMENINO","FEMENINO"),
                   AGE = c(33, 33, 45, 56, 76, 45, 45, 23, 56, 45,
                           19, 23, 45, 56, 28, 36, 53, 49, 47, 22))

value_frequency <- function(variable, value){
        variable <- data$variable
        table <- table(data$variable)
        frequency<- table[[value]]}

value_frequency (SEX, FEMENINO)

Error in frecuencia_valor(SEXO, FEMENINO) : object 'FEMENINO' not found

Solution

  • Try this:

    value_frequency <- function(variable, value){
      variable <- data[,variable]
      table <- table(variable)
      frequency <- table[value]
      return(frequency)
      }
    
    value_frequency ("SEX", "FEMENINO")
    FEMENINO 
          15 
    

    Or a bit shorter, returning only the value, not the associated name:

    value_frequency <- function(variable, value){
      return(table(data[,variable])[[value]])
      }