制作一张比较两年间类别的表格,使用R。

huangapple go评论76阅读模式
英文:

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
  &lt;dbl&gt; &lt;chr&gt;     &lt;dbl&gt;
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 |&gt; pivot_wider(names_from = year,
                  values_from = amount)

# A tibble: 3 &#215; 3
  category `2022` `2023`
  &lt;chr&gt;     &lt;dbl&gt;  &lt;dbl&gt;
1 Rent         10      8
2 Grocery      11     NA
3 Shopping     NA      9

data

df &lt;- tibble(year = c(2022, 2022, 2023, 2023),
             category = c(&quot;Rent&quot;, &quot;Grocery&quot;, &quot;Rent&quot;, &quot;Shopping&quot;),
             amount = c(10,11,8,9))


</details>



huangapple
  • 本文由 发表于 2023年6月1日 08:14:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76377973.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定