Michael Budnick
2013-Sep-10 20:06 UTC
[R] Subtracting elements of a vector from each other stepwise
I am trying to figure out how to create a loop that will take the difference of each member of a vector from each other and also spit out which one has the least difference. I do not want the vector member to subtract from itself or it must be able to disregard the 0 obtained from subtracting from itself. For example: x = c(17,19,23,29) 1. abs(x-x[1]) = (0, 2, 6, 12) 2. abs(x-x[2]) = (2, 0, 4, 10) 3. abs(x-x[3]) = (6, 4, 0, 6) 4. abs(x-x[4]) = (12, 10, 6, 0) The code would then spit out that x[1] and x[2] are the least different, but if there were 2 separate values that were equal the program would recognize them as least different. A little extra help would be to also make this go down row by row through horizontal vectors. I am new to R and all my for loops I'm trying come back null. Thanks for any help. [[alternative HTML version deleted]]
Hi,
Not sure this is what you wanted:
?sapply(seq_along(x), function(i) {x1<- x[i]; x2<- x[-i];
x3<-x2[which.min(abs(x1-x2))];c(x1,x3)})
#???? [,1] [,2] [,3] [,4]
#[1,]?? 17?? 19?? 23?? 29
#[2,]?? 19?? 17?? 19?? 23
A.K.
----- Original Message -----
From: Michael Budnick <mbudnick08 at snet.net>
To: r-help at r-project.org
Cc:
Sent: Tuesday, September 10, 2013 4:06 PM
Subject: [R] Subtracting elements of a vector from each other stepwise
I am trying to figure out how to create a loop that will take the
difference of each member of a vector from each other and also spit out
which one has the least difference.
I do not want the vector member to subtract from itself or it must be able
to disregard the 0 obtained from subtracting from itself.
For example:
x = c(17,19,23,29)
1. abs(x-x[1]) = (0, 2, 6, 12)
2. abs(x-x[2]) = (2, 0, 4, 10)
3. abs(x-x[3]) = (6, 4, 0, 6)
4. abs(x-x[4]) = (12, 10, 6, 0)
The code would then spit out that x[1] and x[2] are the least different,
but if there were 2 separate values that were equal the program would
recognize them as least different.
A little extra help would be to also make this go down row by row through
horizontal vectors.
I am new to R and all my for loops I'm trying come back null.
Thanks for any help.
??? [[alternative HTML version deleted]]
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Maybe Matching Threads
- Adding elements in data.frame subsets and also subtracting an element from the rest elements in data.frame
- [PATCH 0/2] vdpa/snet: support [s/g]et_vq_state and suspend
- [PATCH resend 0/2] vdpa/snet: support [s/g]et_vq_state and suspend
- [PATCH] vdpa/snet: implement the resume vDPA callback
- Subtracting elements of data.frame