gpt4 book ai didi

r - 如何向 data.frame 的每组添加数字序列?

转载 作者:行者123 更新时间:2023-12-02 18:11:43 25 4
gpt4 key购买 nike

我有一个美国邮政编码的数据框,我想在重复其余行的同时向每个唯一的邮政编码添加数字序列。现在,我的数据如下所示:

 zip   city        state_name   
<chr> <chr> <chr>
1 01001 Agawam Massachusetts
2 01002 Amherst Massachusetts
3 01003 Amherst Massachusetts
4 01005 Barre Massachusetts
5 01007 Belchertown Massachusetts

对于每一行,我希望它看起来像这样,(对于每个邮政编码。)

 zip   city        state_name    Num
<chr> <chr> <chr>
01001 Agawam Massachusetts .8
01001 Agawam Massachusetts 1.0
01001 Agawam Massachusetts 1.2
01001 Agawam Massachusetts 1.4

其余行依此类推。

此处的数据:

structure(list(zip = c("01001", "01002", "01003", "01005", "01007"
), city = c("Agawam", "Amherst", "Amherst", "Barre", "Belchertown"
), state_name = c("Massachusetts", "Massachusetts", "Massachusetts",
"Massachusetts", "Massachusetts")), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))

最佳答案

如果我理解您的问题,您可以使用 dplyr 中的 group_bysummarize 来完成此操作。

library("dplyr")

df |>
group_by(across(everything())) |>
summarize(Num=seq(0.8, 1.4, 0.2)) |>
ungroup()

# A tibble: 20 × 4
zip city state_name Num
<chr> <chr> <chr> <dbl>
1 01001 Agawam Massachusetts 0.8
2 01001 Agawam Massachusetts 1
3 01001 Agawam Massachusetts 1.2
4 01001 Agawam Massachusetts 1.4
5 01002 Amherst Massachusetts 0.8
6 01002 Amherst Massachusetts 1
7 01002 Amherst Massachusetts 1.2
8 01002 Amherst Massachusetts 1.4
9 01003 Amherst Massachusetts 0.8
10 01003 Amherst Massachusetts 1
11 01003 Amherst Massachusetts 1.2
12 01003 Amherst Massachusetts 1.4
13 01005 Barre Massachusetts 0.8
14 01005 Barre Massachusetts 1
15 01005 Barre Massachusetts 1.2
16 01005 Barre Massachusetts 1.4
17 01007 Belchertown Massachusetts 0.8
18 01007 Belchertown Massachusetts 1
19 01007 Belchertown Massachusetts 1.2
20 01007 Belchertown Massachusetts 1.4

关于r - 如何向 data.frame 的每组添加数字序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72222841/

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