R将列的每个数据值与列中的其余值进行比较?

时间:2021-04-08 13:09:16

I would like to create a function that looks at a column of values. from those values look at each value individually, and asses which of the other data points value is closest to that data point. I'm guessing it could be done by checking the length of the data frame, making a list of the respective length in steps of 1. Then use that list to reference which cell is being analysed against the rest of the column. though I don't know how to implement that. eg. data:

我想创建一个查看一列值的函数。从这些值中单独查看每个值,并评估哪个其他数据点值最接近该数据点。我猜测它可以通过检查数据帧的长度来完成,以1为步长列出各自的长度。然后使用该列表来引用正在分析哪个单元格与列的其余部分。虽然我不知道如何实现它。例如。数据:

  1. 20
  2. 17
  3. 29
  4. 33

    • 1) is closest to 2)
    • 1)最接近2)

    • 2) is closest to 1)
    • 2)最接近1)

    • 3) is closest to 4)
    • 3)最接近4)

    • 4) is closest to 3)
    • 4)最接近3)

  5. 33 1)最接近2)2)最接近1)3)最接近4)4)最接近3)

I found this example which tests for similarity but id like to know what letter is assigns to.

我找到了这个测试相似性的例子,但想知道什么字母是分配的。

x=c(1:100)
your.number=5.43
which(abs(x-your.number)==min(abs(x-your.number)))

Also if you know how I could do this, could you expain the parts of the code and what they mean?

此外,如果你知道我怎么做,你能否得到代码的部分及其含义?

1 个解决方案

#1


I wrote a quick function that does the same thing as the code you provided.

我编写了一个快速函数,它与您提供的代码完全相同。

The code you provided takes the absolute value of the difference between your number and each value in the vector, and compares that the minimum value from that vector. This is the same as the which.min function that I use below. I go through my steps below. Hope this helps.

您提供的代码采用数字与向量中每个值之间的差值的绝对值,并将该值与该向量的最小值进行比较。这与我在下面使用的which.min函数相同。我按照下面的步骤进行操作。希望这可以帮助。

Make up some data

弥补一些数据

a = 1:100
yourNumber = 6

Where Num is your number, and x is a vector

Num是你的数字,x是矢量

getClosest=function(x, Num){
 return(which.min(abs(x-Num)))
}

Then if you run this command, it should return the index for the value of the vector that corresponds to the closest value to your specified number.

然后,如果运行此命令,它应返回与您指定数字的最接近值对应的向量值的索引。

getClosest(x=a, Num=yourNumber)

#1


I wrote a quick function that does the same thing as the code you provided.

我编写了一个快速函数,它与您提供的代码完全相同。

The code you provided takes the absolute value of the difference between your number and each value in the vector, and compares that the minimum value from that vector. This is the same as the which.min function that I use below. I go through my steps below. Hope this helps.

您提供的代码采用数字与向量中每个值之间的差值的绝对值,并将该值与该向量的最小值进行比较。这与我在下面使用的which.min函数相同。我按照下面的步骤进行操作。希望这可以帮助。

Make up some data

弥补一些数据

a = 1:100
yourNumber = 6

Where Num is your number, and x is a vector

Num是你的数字,x是矢量

getClosest=function(x, Num){
 return(which.min(abs(x-Num)))
}

Then if you run this command, it should return the index for the value of the vector that corresponds to the closest value to your specified number.

然后,如果运行此命令,它应返回与您指定数字的最接近值对应的向量值的索引。

getClosest(x=a, Num=yourNumber)