【问题标题】:matching values in dataframe to other in group_by将数据框中的值与 group_by 中的其他值匹配
【发布时间】:2018-02-13 16:35:33
【问题描述】:

我正在使用 R 中的数据集,并且我有一个带有“名称、纬度、经度和计数”的数据框。如果我 group_by name 我得到 3 行如果我 group_by longitude 我得到 6 行,因为经度不匹配。这是不正确的,它们应该是两者之一。

name <- c("loc_1", "loc_1", "loc_2", "loc_2", "loc_3", "loc_3")
latitude <- c(44.359, 44.359, 44.479, 44.479, 43.522, 43.522)
longitude <- c(-89.839, -89.837, -88.137, -88.130, -89.774, -89.771)
total <- c(9, 6506, 6506, 5, 12966, 351)
t1 <- data.frame(name, latitude, longitude, total)


    name  latitude longitude  total
1  loc_1   44.359   -89.839   9
2  loc_1   44.359   -89.837   6506
3  loc_2   44.479   -88.137   6002
4  loc_2   44.479   -88.130   5
5  loc_3   43.522   -89.774   12966
6  loc_3   43.522   -89.771   351

我需要更改其中一个经度以匹配另一个它们靠得很近,所以我不担心。我没有太多要添加的内容,除了一次全部更改它们之外,这对于大型数据集来说将永远需要。

    name  latitude longitude  total
1  loc_1   44.359   -89.837   6515
2  loc_2   44.479   -88.137   6007
3  loc_3   43.522   -89.774   13,317

现在每个位置的总数都是正确的,并且可以用每个位置一个点进行映射。

【问题讨论】:

  • 您想按名称和纬度分组吗?
  • 这是一个更大的数据集的子集 group_by 用于测试以发现此类错误。我只想要 3 个位置,每个位置都有 lat、lon 和 total。
  • 为什么还要按经度分组?不是每个位置的经度或纬度都大致相同吗?
  • 是的,非常接近,但我需要它们相同。这是来自传感器的读数,我猜传感器在几分钟内返回错误的经度。这些数据将在某个时间点进行映射,我不会为每个位置只加一个点。

标签: r


【解决方案1】:

鉴于你对我的评论的回答,你可以试试这个:

library(dplyr)
t1 %>% group_by(name) %>% 
  summarise(latitude = as.numeric(names(sort(table(latitude), decreasing = TRUE)))[1],
            longitude = as.numeric(names(sort(table(longitude), decreasing = TRUE)))[1],
            total = sum(total))

它选择最常出现的纬度和经度并将总数相加。如果您还没有计算其中的一些,也许您需要将 sum(total) 更改为 n()...

【讨论】:

  • 谢谢蒂诺,这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 2020-02-17
  • 1970-01-01
  • 2015-11-21
  • 1970-01-01
  • 2018-05-01
  • 1970-01-01
  • 2020-06-16
  • 2021-04-17
相关资源
最近更新 更多