[英]From two vectors in R, find the min in the second vector greater than each value in the first
我在R中有兩個向量:
> x <- c(323, 344, 383, 404, 428, 444, 1447, 1466, 1492, 1512)
> y <- c(329, 389, 1453, 1465, 1498, 1511)
我需要一個帶x的數據框和y大於x的最小值,所以這是我正在尋找的結果集:
> data.frame(
x = c(323, 344, 383, 404, 428, 444, 1447, 1466, 1492, 1512),
y = c(329, 389, 389, 1453, 1453, 1453, 1453, 1498, 1498, NA)
)
我嘗試過子集,類似於:
> x_data_frame <- data.frame(a = x) #create the frame
> x_data_frame$b <- min(y[y > x]) #calculation
但是,當然,這不起作用。 有任何想法嗎?
您可以循環遍歷x
並根據您的條件構造一個向量:
data.frame(x, y = sapply(x, function(i) dplyr::na_if(min(y[y>i]), Inf)))
# x y
#1 323 329
#2 344 389
#3 383 389
#4 404 1453
#5 428 1453
#6 444 1453
#7 1447 1453
#8 1466 1498
#9 1492 1498
#10 1512 NA
使用的na_if()
函數從dplyr
更換Inf
值為NA
,你可以,如果忽略它Inf
值是罰款您的分析。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.