Closest value to a specific column in R

前端 未结 4 924
自闭症患者
自闭症患者 2021-02-13 06:26

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          


        
4条回答
  •  再見小時候
    2021-02-13 06:51

    Here is another approach using matrixStats

    x <- as.matrix(data[,-3L])
    y <- abs(x - .subset2(data, 3L))
    x[matrixStats::rowMins(y) == y]
    # [1] 24 30 20
    

    Or in base using vapply

    x <- as.matrix(data[,-3L])
    y <- abs(x - .subset2(data, 3L))
    vapply(1:nrow(data), 
           function(k) x[k,][which.min(y[k,])], 
           numeric(1))
    # [1] 24 30 20
    

提交回复
热议问题