最接近R中特定列的值 [英] Closest value to a specific column in R
本文介绍了最接近R中特定列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想找到最接近下面x3列的值。
I would like to find the closest value to column x3 below.
data=data.frame(x1=c(24,12,76),x2=c(15,30,20),x3=c(45,27,15))
data
x1 x2 x3
1 24 15 45
2 12 30 27
3 76 20 15
因此所需的输出将是
Closest_Value_to_x3
24
30
20
请帮助。谢谢
推荐答案
使用 max.col(-abs(data [,3]-data [, -3]))
查找最接近值的列位置,并将此结果用作矩阵的一部分,以从数据中提取所需的值。矩阵由 cbind
Use max.col(-abs(data[, 3] - data[, -3]))
to find the column positions of the closest values and use this result as part of a matrix to extract desired values from your data. The matrix is returned by cbind
col <- 3
data[, -col][cbind(1:nrow(data),
max.col(-abs(data[, col] - data[, -col])))]
#[1] 24 30 20
这篇关于最接近R中特定列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文