【问题标题】:Indicate in which consecutive ages the number of people of the following age is most higher than the number of people of the previous age in R指出在哪些连续的年龄中,R中后一个年龄的人数最多高于前一个年龄的人数
【发布时间】:2022-11-23 21:03:31
【问题描述】:

我有一个这样的数据框:

Name= letters[1:5]

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

df <- data.frame(Name, Amount)

问题是我必须连续打印一对姓名数量后面的名字比前面的名字最大。例如,在我的数据框中去向:

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

(b,c) 是 4&9 -> 9-4=5(正确答案)

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

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

所以答案是:乙丙

我尝试过类似 as.data.frame(table(df))count() 的方法来提取所需的值,但没有成功。

【问题讨论】:

  • 我不明白 correct answer 的规则

标签: r dataframe rstudio


【解决方案1】:

你想要diffwhich.max

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

【讨论】:

    【解决方案2】:

    如果你想要一个有差异的专栏,你可以做类似的事情,

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 2011-03-23
      相关资源
      最近更新 更多