Rstudent
Rstudent

Reputation: 885

Match values from a data frame

Is it possible to return the most common duration from a dataset? I would like to return from column 16:00 the highest values corresponding to the duration column: 30 and 60.

Sample output:

![enter image description here

Desired output

Duration: 30 60

Sample data

structure(list(Duration = c(10, 20, 30, 40, 50, 60), `16:00` = c(1, 
0, 3, 0, 1, 3), `16:10` = c(0, 1, 0, 0, 1, 0), `16:20` = c(0, 
0, 0, 2, 1, 0)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L), spec = structure(list(cols = list(
    Duration = structure(list(), class = c("collector_double", 
    "collector")), `16:00` = structure(list(), class = c("collector_double", 
    "collector")), `16:10` = structure(list(), class = c("collector_double", 
    "collector")), `16:20` = structure(list(), class = c("collector_double", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
"collector")), skip = 1L), class = "col_spec"))

Upvotes: 0

Views: 33

Answers (2)

user10917479
user10917479

Reputation:

If you are just looking in column 16:00 as stated, this should work just fine.

df$Duration[df$`16:00` == max(df$`16:00`)]
# [1] 30 60

Upvotes: 1

Karthik S
Karthik S

Reputation: 11548

Does this work:

library(dplyr)
library(tidyr)
df %>% pivot_longer(-Duration) %>% slice_max(order_by = value,n = 1) %>% pull(Duration)
[1] 30 60

Upvotes: 1

Related Questions