gpt4 book ai didi

r - 根据日期创建列

转载 作者:行者123 更新时间:2023-12-01 09:15:23 25 4
gpt4 key购买 nike

我有类似以下的数据,但更大

boat = c(1,1,1,1,1,1,1,2,2,2,2,2,2)
species = c("cod", "haddock", "ling",
"cod", "haddock", "ling", "tusk",
"cod", "haddock", "ling",
"cod", "haddock", "ling")
date = c(as.Date(c("1.03.2017","1.03.2017","1.03.2017",
"2.03.2017", "2.03.2017", "2.03.2017","2.03.2017",
"4.03.2017","4.03.2017","4.03.2017",
"7.03.2017", "7.03.2017", "7.03.2017"), "%d.%m.%Y"))
df <- data.frame(boat, species, date)

df
boat species date
1 cod 01.03.2017
1 haddock 01.03.2017
1 ling 01.03.2017
1 cod 02.03.2017
1 haddock 02.03.2017
1 ling 02.03.2017
1 tusk 02.03.2017
2 cod 04.03.2017
2 haddock 04.03.2017
2 ling 04.03.2017
2 cod 07.03.2017
2 haddock 07.03.2017
2 ling 07.03.2017

我想创建一个附加列,按船顺序排列日期,以便我的数据集如下所示。

    boat  species  date       rank
1 cod 01.03.2017 1
1 haddock 01.03.2017 1
1 ling 01.03.2017 1
1 cod 02.03.2017 2
1 haddock 02.03.2017 2
1 ling 02.03.2017 2
1 tusk 02.03.2017 2
2 cod 04.03.2017 1
2 haddock 04.03.2017 1
2 ling 04.03.2017 1
2 cod 07.03.2017 2
2 haddock 07.03.2017 2
2 ling 07.03.2017 2

我试过下面的代码

library(dplyr)

df %>%
group_by(boat, species) %>%
mutate(Order = rank(date))

但是以前没有出现过的物种在第一次出现时会被赋予“1”级。任何帮助表示赞赏。

最佳答案

我们可以使用 dplyr 中的 group_bydense_rank 来创建所需的输出。

library(dplyr)

df2 <- df %>%
group_by(boat) %>%
mutate(rank = dense_rank(date))

df2
# A tibble: 13 x 4
# Groups: boat [2]
boat species date rank
<dbl> <fctr> <date> <int>
1 1 cod 2017-03-01 1
2 1 haddock 2017-03-01 1
3 1 ling 2017-03-01 1
4 1 cod 2017-03-02 2
5 1 haddock 2017-03-02 2
6 1 ling 2017-03-02 2
7 1 tusk 2017-03-02 2
8 2 cod 2017-03-04 1
9 2 haddock 2017-03-04 1
10 2 ling 2017-03-04 1
11 2 cod 2017-03-07 2
12 2 haddock 2017-03-07 2
13 2 ling 2017-03-07 2

关于r - 根据日期创建列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45882247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com