此问题是此topic的变体,但我不确定为什么我没有得到正确的结果。
我的数据:
dput(temp)
structure(list(MB = c("4001826", "4007824", "4007948", "4010876",
"4015215"), Margin = c(900, 30733.0616, 15525, 2689.05865, 4340
), T1 = c(300, 11296.491, 38810, 1379.44, 870), T2 = c(360, 12706.491,
46404, 1466.44, 1050), T3 = c(390, 13430.491, 49781, 1574.44,
1141), T4 = c(420, 15146.491, 55274, 1720.44, 1230), T5 = c(900,
30972.2633, 109829.852, 1807.44, 2670), T6 = c(960, 41017.3059,
119443.9056, 2718.2, 2850), T7 = c(1020, 42079.3059, 128232.9056,
2907.2, 3020), T8 = c(1200, 44461.3059, 151137.9056, 3314.2,
3540), T9 = c(1500, 46936.3059, 180746.9056, 3746.2, 4400), T10 = c(1800,
48246.3059, 199116.9056, 3746.2, 5260), T11 = c(1530, 35279.3059,
144154.9056, 2748.2, 4415), T12 = c(1500, 33350.3059, 138818.9056,
2881.2, 4330), T13 = c(1500, 34719.3059, 140508.9056, 2893.2,
4330), T14 = c(1800, 58092.3059, 205687.9056, 2463.2, 5220),
T15 = c(390, 35438.0846, 68364.8492, 2987.1718, 1172), T16 = c(390,
32038.0139, 64451.0925, 2655.5102, 1162), T17 = c(390, 30219.2716,
67860.3977, 2462.239, 1162), T18 = c(608.397, 49543.5875,
113689.9478, 3643.7126, 1872), T19 = c(660, 34080.84615,
85176.3018, 2284.9598, 1923)), .Names = c("MB", "Margin",
"T1", "T2", "T3", "T4", "T5", "T6", "T7", "T8", "T9", "T10",
"T11", "T12", "T13", "T14", "T15", "T16", "T17", "T18", "T19"
), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))
我想要做的是找到一个具有最接近值(小于或等于)保证金的T组。所以我的规则是:
我做了这个尝试:
temp <- gather(temp, Closest_column, val, T1:T19) %>%
group_by(MB) %>%
slice(max(which(val <= Margin)[1]))
但是有两个奇怪的事情发生了。首先,temp变量返回4行,而不是5.然后,结果不正确:
head(temp)
# A tibble: 4 x 4
# Groups: MB [4]
MB Margin Closest_column val
<chr> <dbl> <chr> <dbl>
1 4001826 900.000 T1 300.00
2 4007824 30733.062 T1 11296.49
3 4010876 2689.059 T1 1379.44
4 4015215 4340.000 T1 870.00
对于 4001826 ,指定的最近列是T1,但它应该是T5,其值相等(Margin = 900.00,T5 = 900.00)。
对于 4007824 ,它应该是T17,这是保证金中最小的(保证金= 30733.062,T17 = 30219.27)。
我发现错误的任何线索?