r - 如何基于列聚合数据

标签 r postgresql dplyr

我是 R 的新手,我想弄清楚如何将数据组合成一种独特的格式,然后将该数据输入到 postgres 数据库中。下面是提供格式示例的代码:

df <- data.frame("1"=c("us","fr","us","fr","de", "de"), "2"=c(35, 20, 35, 20, 22.25, 125), "3"=c(105, -67.56, 105, -67.56, 138, 12), "4"=c(100, 200, 80, 160, 50, 18))

colnames(df) <-  c(
    "countryAbr",
    "latitude",
    "longitude",
    "countOfResidents"
    )

这是当前的数据集:

  countryAbr latitude longitude countOfResidents
1         us    35.00    105.00              100
2         fr    20.00    -67.56              200
3         us    35.00    105.00               80
4         fr    20.00    -67.56              160
5         de    22.25    138.00               50
6         de    125      12                   18

我想根据一个国家/地区的总出现次数合并数据,同时考虑唯一和重复的纬度和经度坐标。我也想把居民的总和合并起来。这是我预期的最终结果:

  countryAbr TotalCountryOccurances TotalResidentCount
1         us                      2                180
2         fr                      2                360
3         de                      2                 68

我使用计数函数来获取国家/地区的总出现次数(我想??),但不确定如何组合所有内容以及使用什么函数。

countryCount <- count(df[,c("latitude", "longitude")])

当我确实有最终的数据集时,我想把它放到一个postgres表中供前端查询和使用。我知道如何做后者,但不确定如何将 R 数据导入 Postgres 表。

** 编辑以明确重复和唯一的纬度和经度**

最佳答案

如果你想计算行数并对每个唯一的countryAbr的居民人数求和,你可以使用dplyr汇总countryAbr 分组后的这些计数:

library(dplyr)
result <- df %>% group_by(countryAbr) %>% 
                 summarise(TotalCountryOccurances=n(), TotalResidentCount=sum(countOfResidents))

由于我们按 countryAbr 中的每个唯一值进行分组,函数 n() 返回组的行数,函数 sum 计算组的 countOfResidents 列的总和。在这种情况下,对于 countryAbr 中的每个唯一值,行数和总和是针对 latitudelongitude 的所有值计算的。我假设这就是您的意思:

taking into account both unique and duplicate latitude and longitude coordinates.

根据您提供的数据:

print(result)
### A tibble: 3 x 3
##  countryAbr TotalCountryOccurances TotalResidentCount
##      <fctr>                  <int>              <dbl>
##1         de                      1                 50
##2         fr                      2                360
##3         us                      2                180

关于r - 如何基于列聚合数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39553108/

相关文章:

r - 使用孤立节点创建 igraph

r - 如何在 R 中重复序列但在重复时调整向量中的值?

postgresql - 如何正确分组 Postgres 数据

r - 在 mutate 中应用函数

r - 将列名传递给 R dplyr group_by 和汇总函数

r - 使用 dplyr 和 mutate 计算满足条件的列数

r - 在 data.table 中查找匹配项的行索引(我可以进行二分搜索吗?)

r - 在 R/Rcpp 中转置列表的最快方法

postgresql - 将 PostgreSQL 密码加密从 MD5 更改为 SHA

python - 使用 .format() 时出现 psycopg2 编程错误