Home > Software engineering >  Indicate in which consecutive ages the number of people of the following age is most higher than the
Indicate in which consecutive ages the number of people of the following age is most higher than the

Time:11-23

I have a dataframe like this:

Name= letters[1:5]

Amount <- c(1, 4, 9, 2, 0)

df <- data.frame(Name, Amount)

The problem is I have to print a pair of consecutive Name that the Amount of the name after is the most larger than the name previous. For example, in my data frame df:

(a,b) is 1&4 -> 4-1=3

(b,c) is 4&9 -> 9-4=5 (Correct answer)

(c,d) is 9&2 -> 9-2=-7

(d,e) is 2&0 -> 2-0=2

So the answer would be : b c

I have tried something like as.data.frame(table(df)) and count() to extract the desired value but it didn't work.

CodePudding user response:

You want diff and which.max.

with(df, Name[which.max(diff(Amount))   0:1])
#> [1] "b" "c"

CodePudding user response:

If you want a column with the differences you could do something like,

df <- mutate(df, Diff=Amount-lag(Amount)) # get a new column with the difference

Name    Amount  Diff
<chr>   <dbl>   <dbl>
a   1   NA
b   4   3
c   9   5
d   2   -7
e   0   -2
  • Related