R 中跨两个以上不同数据帧的计算
Calculations across more than two different dataframes in R
我正在尝试将之前在 Excel 中完成的一些工作转移到 R 中。我需要做的就是将两个基本 count_if 公式转换为可读的 R 脚本。在 Excel 中,我会使用三个 table 并使用 'point-and-click' 方法计算它们,但现在我不知道应该如何在 R 中解决它。
我的原始数据帧很大,所以对于这个问题我发布了示例数据帧:
OperatorData <- data.frame(
Operator = c("A","B","C"),
Locations = c(850, 575, 2175)
)
AreaData <- data.frame(
Area = c("Torbay","Torquay","Tooting","Torrington","Taunton","Torpley"),
SumLocations = c(1000,500,500,250,600,750)
)
OperatorAreaData <- data.frame(
Operator = c("A","A","A","B","B","B","C","C","C","C","C"),
Area = c("Torbay","Tooting","Taunton",
"Torbay","Taunton","Torrington",
"Tooting","Torpley","Torquay","Torbay","Torrington"),
Locations = c(250,400,200,
100,400,75,
100,750,500,650,175)
)
我想做的是向 OperatorData 数据框添加两列:一列表示操作员在其中操作的区域数量,另一列表示操作员在其中操作的区域数量 并且 拥有超过 50% 的位置。
所以新的结果数据框看起来像这样
Operator Locations AreaCount Own_GE_50percent
A 850 3 1
B 575 3 1
C 2715 5 4
到目前为止,我已经设法使用 table 函数计算出第一列,然后附加:
OpAreaCount <- data.frame(table(OperatorAreaData$Operator))
names(OpAreaCount)[2] <- "AreaCount"
OperatorData$"AreaCount" <- cbind(OpAreaCount$AreaCount)
这很简单,但我卡在如何计算第二列计算条件为 50%。
library(dplyr)
OperatorAreaData %>%
inner_join(AreaData, by="Area") %>%
group_by(Operator) %>%
summarise(AreaCount = n_distinct(Area),
Own_GE_50percent = sum(Locations > (SumLocations/2)))
# # A tibble: 3 x 3
# Operator AreaCount Own_GE_50percent
# <fct> <int> <int>
# 1 A 3 1
# 2 B 3 1
# 3 C 5 4
如果您确定每个 Operator
都有唯一的 Area
值,则可以使用 AreaCount = n()
。
我正在尝试将之前在 Excel 中完成的一些工作转移到 R 中。我需要做的就是将两个基本 count_if 公式转换为可读的 R 脚本。在 Excel 中,我会使用三个 table 并使用 'point-and-click' 方法计算它们,但现在我不知道应该如何在 R 中解决它。
我的原始数据帧很大,所以对于这个问题我发布了示例数据帧:
OperatorData <- data.frame(
Operator = c("A","B","C"),
Locations = c(850, 575, 2175)
)
AreaData <- data.frame(
Area = c("Torbay","Torquay","Tooting","Torrington","Taunton","Torpley"),
SumLocations = c(1000,500,500,250,600,750)
)
OperatorAreaData <- data.frame(
Operator = c("A","A","A","B","B","B","C","C","C","C","C"),
Area = c("Torbay","Tooting","Taunton",
"Torbay","Taunton","Torrington",
"Tooting","Torpley","Torquay","Torbay","Torrington"),
Locations = c(250,400,200,
100,400,75,
100,750,500,650,175)
)
我想做的是向 OperatorData 数据框添加两列:一列表示操作员在其中操作的区域数量,另一列表示操作员在其中操作的区域数量 并且 拥有超过 50% 的位置。
所以新的结果数据框看起来像这样
Operator Locations AreaCount Own_GE_50percent
A 850 3 1
B 575 3 1
C 2715 5 4
到目前为止,我已经设法使用 table 函数计算出第一列,然后附加:
OpAreaCount <- data.frame(table(OperatorAreaData$Operator))
names(OpAreaCount)[2] <- "AreaCount"
OperatorData$"AreaCount" <- cbind(OpAreaCount$AreaCount)
这很简单,但我卡在如何计算第二列计算条件为 50%。
library(dplyr)
OperatorAreaData %>%
inner_join(AreaData, by="Area") %>%
group_by(Operator) %>%
summarise(AreaCount = n_distinct(Area),
Own_GE_50percent = sum(Locations > (SumLocations/2)))
# # A tibble: 3 x 3
# Operator AreaCount Own_GE_50percent
# <fct> <int> <int>
# 1 A 3 1
# 2 B 3 1
# 3 C 5 4
如果您确定每个 Operator
都有唯一的 Area
值,则可以使用 AreaCount = n()
。