Reputation: 152
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
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