Note that k
is the value of n
, where Mode
is equal to 1
. However, in this case below, I have two values where Mode
is equal to 1
, which is n = 2
and n = 4
. So I would like to make some condition or something like that, that this will happen, considering the case where M1
is equal to 1
, in this case, the first alternative, that is, n = 2
. So k
would be equal to 2.
df1<-structure(list(n= c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20), M1 = c(1L, 3L, 2L, 19L,
18L, 16L, 17L, 14L, 15L, 13L, 12L, 7L, 6L, 8L, 9L, 10L, 11L,
4L, 5L), M2 = c(1L, 3L, 2L, 19L, 18L, 16L, 17L, 14L,
15L, 13L, 12L, 7L, 6L, 8L, 9L, 10L, 11L, 4L, 5L), M3 = c(3L,
2L, 1L, 19L, 18L, 16L, 17L, 14L, 15L, 13L, 12L, 7L, 6L, 8L, 9L,
10L, 11L, 4L, 5L), M4 = c(2L, 3L, 1L, 19L, 18L, 16L,
17L, 14L, 15L, 13L, 12L, 7L, 6L, 8L, 9L, 10L, 11L, 4L, 5L), Mode = c(1,
3, 1, 19, 18, 16, 17, 14, 15, 13, 12, 7, 6, 8, 9, 10, 11, 4,
5), Percentage = c("50%", "75%", "50%", "100%", "100%", "100%",
"100%", "100%", "100%", "100%", "100%", "100%", "100%", "100%",
"100%", "100%", "100%", "100%", "100%")), class = "data.frame", row.names = c(NA,
-19L))
n M1 M2 M3 M4 Mode Percentage
1 2 1 1 3 2 1 50%
2 3 3 3 2 3 3 75%
3 4 2 2 1 1 1 50%
4 5 19 19 19 19 19 100%
5 6 18 18 18 18 18 100%
6 7 16 16 16 16 16 100%
7 8 17 17 17 17 17 100%
8 9 14 14 14 14 14 100%
9 10 15 15 15 15 15 100%
10 11 13 13 13 13 13 100%
11 12 12 12 12 12 12 100%
12 13 7 7 7 7 7 100%
13 14 6 6 6 6 6 100%
14 15 8 8 8 8 8 100%
15 16 9 9 9 9 9 100%
16 17 10 10 10 10 10 100%
17 18 11 11 11 11 11 100%
18 19 4 4 4 4 4 100%
19 20 5 5 5 5 5 100%
k<-subset(df1, Mode==1)$n
> k
[1] 2 4
CodePudding user response:
match
is a good way to find the first n
for which Mode == 1
k = with(df1[order(df1$M1), ], n[match(1, Mode)])
k
# [1] 2
Change df1[order(df1$M1), ]
to df1[order(df1$M1, df1$M2, df1$M3, ...), ]
if you want to use additional columns as tie breakers.
If you need to generalize this to modes that are not first in the default sort order (like 1
is in your sample data), do it like this:
m = 1
k = with(df1[order(df1$M1 == m, decreasing = TRUE), ], n[match(m, Mode)])