Most frequent from data table

Viewed 105

Please find below my sample data.

I would like to identify the frequent as well the frequencies from the column named 'Start/End' as it 'Duration'. Any help is welcomed

structure(list(serial = c(19050112, 19050112, 12201018, 17221212, 
19300613, 19050112, 13260115, 16151202, 16310311, 14291209, 12190516, 
15160311, 12201018, 34080603, 17221212, 19300613, 19050112, 15040801, 
13260115, 16151202), `Start/End` = c("t0730_0745 - t0730_0745", 
"t0745_0800 - t0745_0800", "t0800_0815 - t0800_0815", "t0800_0815 - t0800_0815", 
"t0800_0815 - t0800_0815", "t0800_0815 - t0800_0815", "t0800_0815 - t0800_0815", 
"t0800_0815 - t0800_0815", "t0800_0815 - t0800_0815", "t0800_0815 - t0800_0815", 
"t0800_0815 - t0800_0815", "t0800_0815 - t0800_0815", "t0815_0830 - t0815_0830", 
"t0815_0830 - t0815_0830", "t0815_0830 - t0815_0830", "t0815_0830 - t0815_0830", 
"t0815_0830 - t0815_0830", "t0815_0830 - t0815_0830", "t0815_0830 - t0815_0830", 
"t0815_0830 - t0815_0830"), Duration = c(2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), 
    Frequency = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)), row.names = c(NA, -20L
), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x000001824bb61ef0>)
2 Answers

We can use data.table methods

library(data.table)
df1[, .(new = unlist(tstrsplit(`Start/End`, " - ")))][, 
          .N, new][N == max(N)]
#          new  N
#1: t0800_0815 20

You can split the string on " - ", calculate it's frequency using table and get the most frequently occurring value.

sort(table(unlist(strsplit(df1$`Start/End`, ' - '))), decreasing = TRUE)[1]
#t0800_0815 
#        20 

To get all values of similar frequency we can use :

tab <- table(unlist(strsplit(df1$`Start/End`, ' - ')))
tab[tab == max(tab)]
Related