R is the return value based on the position

I was wondering if there is a way to pull out a value based on a position in a vector, so for example, I have a data frame with two vectors, I grouped them from raw on V1 and them on V2, much like ORDER BY in SQL. My problem arises when I try to pull the 3rd Min on the type of group V1.

Ordered data frame ...

V1  V2
Ford    18
Ford    16
Ford    15
Ford    14
Ford    12
**Ford  5**
Ford    2
Ford    1
Nisan   10
Nisan   9
Nisan   8
Nisan   7
Nisan   6
**Nisan     5**
Nisan   4
Nisan   3
Toyota  20
Toyota  19
Toyota  15
Toyota  12
Toyota  11
**Toyota    10**
Toyota  6
Toyota  2

Result I want in a new data frame, a 3-minute value for the variable ...

V1 V2
Ford 5
Nisan 5
Toyota 10

Thanks in advance.

+4
source share
2 answers

With base R you can do something like

aggregate(V2 ~ V1, df[order(df$V2), ], `[`, 3L)
#       V1 V2
# 1   Ford  5
# 2  Nisan  5
# 3 Toyota 10

Or (per @akruns comment) using ave

df[with(df, ave(V2, V1, FUN = order)) == 3L,]
+6
source

Try

library(data.table)#v1.9.5+
setDT(df1)[order(V2), list(V2=V2[3L]), by = V1]

Or as @DavidArenburg mentioned in the comments

setDT(df1)[, .SD[frank(V2, ties.method = "dense") == 3L], by = V1]

or

library(dplyr)
 df1 %>% 
     group_by(V1) %>%
     filter(rank(V2)==3)

or

 df1 %>%
     group_by(V1) %>% 
     arrange(V2) %>%
     slice(3L)
+6
source

All Articles