1

Is there a way to check which value in a vector/column is nearest to a given value?

so for example I have column with number of days: days: 50, 49, 59, 180, 170, 199, 200

I want to make a new column in the dataframe that marks an X everytime the dayscolumn has the value 183 or close to 183

It should look like this:

DAYS         new column
0            
12
12
14
133
140           X
0
12
14
15
178 
183           X
0
15
30
72
172           X

Hope you can help me!

Jaap
  • 81,064
  • 34
  • 182
  • 193

1 Answers1

0

You're searching for local maxima, essentially. Start off by normalizing your data to your target, i.e. 183, and search for values closest to zero. Those are your local maxima. I added data with values greater than your target to demonstrate.

df <- data.frame(DAYS = c(0,12,12,14,133,140,0,12,14,15,178,183,184,190,0,15,30,72,172,172.5))
df$localmin <- abs(df$DAYS - 183)
df

> df
    DAYS localmin
1    0.0    183.0
2   12.0    171.0
3   12.0    171.0
4   14.0    169.0
5  133.0     50.0
6  140.0     43.0
7    0.0    183.0
8   12.0    171.0
9   14.0    169.0
10  15.0    168.0
11 178.0      5.0
12 183.0      0.0
13 184.0      1.0
14 190.0      7.0
15   0.0    183.0
16  15.0    168.0
17  30.0    153.0
18  72.0    111.0
19 172.0     11.0
20 172.5     10.5


targets <- which(diff(sign(diff(c(df$localmin, 183)))) == 2) + 1L
df$targets <- 0
df$targets[targets] <- 1
df

> df
    DAYS localmin targets
1    0.0    183.0       0
2   12.0    171.0       0
3   12.0    171.0       0
4   14.0    169.0       0
5  133.0     50.0       0
6  140.0     43.0       1
7    0.0    183.0       0
8   12.0    171.0       0
9   14.0    169.0       0
10  15.0    168.0       0
11 178.0      5.0       0
12 183.0      0.0       1
13 184.0      1.0       0
14 190.0      7.0       0
15   0.0    183.0       0
16  15.0    168.0       0
17  30.0    153.0       0
18  72.0    111.0       0
19 172.0     11.0       0
20 172.5     10.5       1
Anonymous coward
  • 2,061
  • 1
  • 16
  • 29
  • I have tried this, but its does not mark every half year or close? –  Dec 19 '18 at 08:00
  • What if i have dates? so instead of the DAYS column i have dates ex: ("2015-02-10"). And I like to make a new column that marks when there has been 1 year between the dates? Can you use the same method here? And how? –  Dec 19 '18 at 11:11
  • What is it marking, and what format is your data? If you have dates, you can convert to day of the year. 1 year between what dates? You should either edit your question to ask your question, or open a new question. And [make it reproducible](https://stackoverflow.com/a/5963610/2359523), especially if your data is not in the format you posted here. – Anonymous coward Dec 19 '18 at 15:49