0

I have a data frame as below:

df <- data.frame(code=c(1,1,1,1,1,1,2,2,2,2),idp=c(120,140),
p_origin=c("yes","yes","no","yes","yes"),returnee=c("yes","no"))

I want to take average of idp group by code and mode of p_origin which is "yes" here and mode of returnee that is if yes is the mode yes should be in column and if no is the mode "no" should be in column if they have equal number of yes and no the "no_sense" should be in column what I want is as below

output <- data.frame(code=c(1,1,1,1,1,1,2,2,2,2),idp=c(120,140),
p_origin=c("yes","yes","no","yes","yes"),returnee=c("yes","no"),
 average_idp=130, Most_frquent_origin="yes",Most_frequent_returnee="no_sense")

I am doing to take average of as below

iset_df <- iset_df %>% group_by(code) %>% 
            mutate(averag_idp=mean(idp)) %>% 
            mutate(most_frequent_origin=mode(p_origin)

Average is perfect but for mode it shows "numeric".

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
MaxMiak
  • 197
  • 1
  • 7

1 Answers1

2

Using function Modes in the accepted answer to this SO question:

f <- function(x){
  m <- Modes(x)
  if(length(m) > 1) "no sense" else m
}

df %>% 
  group_by(code) %>% 
  mutate(averag_idp = mean(idp), 
         most_frequent_origin = Modes(p_origin),
         most_frequent_returnee = f(returnee))
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • @MaxMiak Glad to help. Note that in the `mutate` there is a call to `Modes` and another to the auxiliary function `f`. This could be changed to 2 calls to `f`. – Rui Barradas Jun 30 '20 at 05:42