Aaron Walton
Aaron Walton

Reputation: 152

Creating function to return variable with largest number of observations

I have a piece of code that works:

    > temp <- as.data.frame(table(df$RUC))
    > temp <- subset(temp, temp$Freq == max(temp$Freq))
    > temp <- as.character(temp$Var1[1])
    > print(temp)
    [1] "England & Wales: Urban city and town"

temp returns exactly what I want, however I want to be able to have it as a function so I don't need to repeat. It returns nothing and I am not sure why.

    > large <- function(a){
    +   temp <- as.data.frame(table(a))
    +   temp <- subset(temp, temp$Freq == max(temp$Freq))
    +   temp <- as.character(temp$Var1[1])
    +   return(temp)
    + }
    > large(df$RUC)
    character(0)

Upvotes: 0

Views: 24

Answers (1)

Will Hipson
Will Hipson

Reputation: 364

I think the problem is subset is turning temp into a factor which behaves a bit differently from a vector. This seems to give the right result:

test_vec <- c("a", "a", "a", "b", "b", "c")

large <- function(a) {
  temp <- as.data.frame(table(a))
  temp <- subset(temp, temp$Freq == max(temp$Freq))[]
  temp <- as.character(temp[[1]])
  return(temp)
}
> large(test_vec)
[1] "a"

Upvotes: 1

Related Questions