[Solved] Create a column based on comparing with a vector and the get the closest number in R [closed]


You can accomplish this as follows:

# create a minimal example data.frame and 
# vector of values to match
df <- data.frame(x = seq(0.1, 1, 0.1))

set.seed(1)
v  <- df$x + rnorm(10, mean = 0, sd = 0.1)

# create a vector z that stores values from v that 
# are closest to values in the ith element of df$x
z <- c()
for(i in 1:nrow(df)){
  z[i] = v[which.min(abs(df$x[i] - v))]
}

# assign the new object z to the data.frame
df$z <- z
df

Which returns:

x          z
1  0.1 0.03735462
2  0.2 0.21643714
3  0.3 0.21836433
4  0.4 0.51795316
5  0.5 0.51795316
6  0.6 0.55952808
7  0.7 0.74874291
8  0.8 0.74874291
9  0.9 0.87383247
10 1.0 0.96946116

1

solved Create a column based on comparing with a vector and the get the closest number in R [closed]