我是 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
中的每个唯一值,行数和总和是针对 latitude
和 longitude
的所有值计算的。我假设这就是您的意思:
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/