gpt4 book ai didi

r - 查询表并生成国家代码分组和绘图条形图的代码

转载 作者:行者123 更新时间:2023-11-29 14:27:52 25 4
gpt4 key购买 nike

我是 R 的新手,并且已经设法将 R 连接到 PostgreSQL 中的数据库,所以我想在 R 中查询这个数据库并生成一个简单的条形图。此条形图应给出前 5 个国家/地区代码的汇总计数。

谁能推荐一个可以做到这一点的查询/脚本?

它基本上是国家的分割,以及每个国家有多少人。

我想将我的数据分解为国家,然后是这些国家的前 5 个

抱歉,我的数据看起来像这样

国家代码
国标

荷兰

美国

国标

国标

不适用

法国

我想计算每个有多少,然后绘制其中的前 5 个,你如何在 R 中做到这一点

最佳答案

这是我将如何连接和查询的一般概述:

library(RPostgreSQL)
library(tidyverse)

pg <- dbDriver("PostgreSQL")

con <- dbConnect(pg, user = "username", password = "your_password",
host="localhost", port = 5432, dbname = "dbname")

tbl(con, "table_name") %>%
group_by(country_code) %>%
summarise(total = n()) %>%
arrange(desc(total)) %>%
head(5) %>%
collect() %>%
as_tibble() %>%
ggplot(aes(reorder(country_code, -total), total)) +
geom_bar(stat = "identity")

关于r - 查询表并生成国家代码分组和绘图条形图的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55855696/

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