dhrice
dhrice

Reputation: 89

R Matching closest number from columns

I have a list of responses to 7 questions from a survey, each their own column, and am trying to find the response within the first 6 that is closest (numerically) to the 7th. Some won't be the exact same, so I want to create a new variable that produces the difference between the closest number in the first 6 and the 7th. The example below would produce 0.

s <- c(1,2,3,4,5,6,3)
s <- t(s)
s <- as.data.frame(s)
s

Any help is deeply appreciated. I apologize for not having attempted code as nothing I have tried has actually gotten close.

Upvotes: 1

Views: 115

Answers (1)

user2602640
user2602640

Reputation: 868

How about this?

which.min( abs(s[1, 1:6] - s[1, 7]))

I'm assuming you want it generalized somehow, but you'd need to provide more info for that. Or just run it through a loop :-)

EDIT: added the loop from the comment and changed exactly 2 tiny things.

s <- c(1,2,3,4,5,6,3) 
t <- c(1,2,3,4,5,6,7) 
p <- c(1,2,3,4,5,6,2) 
s <- data.frame(s,t,p) 
k <- t(s) 
k <- as.data.frame(k) 

k$t <- NA ### need to initialize the column
for(i in 1:3){ 
    ## need to refer to each line of k when populating the t column
    k[i,]$t <- which.min(abs(k[i, 1:6] - k[i, 7])) }

Upvotes: 2

Related Questions