-1

I am more familiar with Python but I need to do this in R. I have a data frame like this:

     id                                               apps
   8400                              10,19,9,9,8,9,1,3,3,6
  10915                           10,2,6,2,3,2,2,3,2,3,2,6
  72331                    10,9,6,1,2,4,6,2,14,3,3,2,3,9,2

I want to count the number of occurrences of each app and then return the app with the most occurrences in a new column:

     id                                               apps     Most
   8400                              10,19,9,9,8,9,1,3,3,6       9
  10915                           10,2,6,2,3,2,2,3,2,3,2,6       2
  72331                    10,9,6,1,2,4,6,2,14,3,3,2,3,9,2       2

Bests.

I added the answer to this case, maybe it helps someone else too :).

Sharek
  • 71
  • 8
  • 3
    `dput` your data please. also, detail how you would do this in python -- we prefer you show some effort in having tried to solve the problem yourself – MichaelChirico Jul 28 '16 at 15:20
  • 6
    "a data frame like this" is ambiguous, thanks to how R prints several things similarly. Anyway, I think you want the mode: http://stackoverflow.com/q/2547402/ – Frank Jul 28 '16 at 15:21
  • `sapply(c("10,19,9,9,8,9,1,3,3,6","10,2,6,2,3,2,2,3,2,3,2,6"),function(x){t<-table(strsplit(x,","));as.numeric(names(which.max(t)))})` could work if your apps column is a string, if it's a list just remove the `strsplit` part. – FisherDisinformation Jul 28 '16 at 15:25
  • @MichaelChirico thanks for your reply. I just found an answer. Bests. – Sharek Jul 28 '16 at 17:35

1 Answers1

0

Let me answer my question, maybe it helps someone else too:

MyMode <-   function(x) {
x <- strsplit(x,",")
names(sort(-table(x)))[1]
}

then apply it:

 df$most <- lapply(as.character(test$apps),MyMode)
Sharek
  • 71
  • 8