英文:
Make a table comparing category between two years in r
问题
我有如下的数据在R中:
year category amount
<dbl> <chr> <dbl>
1 2022 Rent 10
2 2022 Grocery 11
3 2023 Rent 8
4 2023 Shopping 9
我想要制作一个如下的表格:
category 2022 2023
Rent 10 8
Grocery 11
Shopping 9
我考虑过将我的数据从宽格式转换为长格式,或者反之,但我在思考是否有更好的方法。谢谢。
英文:
I have data as such in r:
year category amount
<dbl> <chr> <dbl>
1 2022 Rent 10
2 2022 Grocery 11
3 2023 Rent 8
4 2023 Shopping 9
I would like to make a table as such:
category 2022 2023
Rent 10 8
Grocery 11
Shopping 9
I thought of making my data from either wide to long or vice versa but I am thinking there must be a better way. Thank you.
答案1
得分: 2
我们需要在这里使用tidyr::pivot_wider
函数:
library(tidyr)
df |> pivot_wider(names_from = year,
values_from = amount)
数据:
df <- tibble(year = c(2022, 2022, 2023, 2023),
category = c("Rent", "Grocery", "Rent", "Shopping"),
amount = c(10, 11, 8, 9))
英文:
We need tidyr::pivot_wider
here
library(tidyr)
df |> pivot_wider(names_from = year,
values_from = amount)
# A tibble: 3 × 3
category `2022` `2023`
<chr> <dbl> <dbl>
1 Rent 10 8
2 Grocery 11 NA
3 Shopping NA 9
data
df <- tibble(year = c(2022, 2022, 2023, 2023),
category = c("Rent", "Grocery", "Rent", "Shopping"),
amount = c(10,11,8,9))
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论