我在 R 中有一个数据框,其中的值对应于值估计及其误差范围(MoE)。
列名由模式、指示符字符(e = 估计,m = 误差范围)和匹配估计值和误差范围的ID组成。
因此,列名看起来像“XXXe1, XXXm1, XXXe2, XXXm2, ...”。
目标
我正在尝试创建一个函数(对于每一行)
计算估计值的总和。(这很简单。)
计算总误差。这是每个 MoE 的平方和的平方根。
条件:标记为 0 的估计的 MoE 只能添加一次。
例子:
- 在第 20 行,聚合的 MoE 应该只有
sqrt(123^2)
. - 在第 13 行,B01001e4 和 B01001e5 为 0,因此它们的 MoE 只计算一次。
到目前为止,我已经完成了以下操作来构建一个执行此操作的函数:
estimate_aggregator <- function(DF_to_write_on, New_column_name, source_df, pattern){
subset_df <- source_df[, grepl(pattern, names(source_df))] # I subset all the columns named with the pattern, regardless of whether they are estimate or margin of error
subset_df_e <- source_df[, grepl(paste0(pattern, "e"), names(source_df))] # I create a table with only the estimated values to perform the sum
DF_to_write_on[paste0(New_column_name, "_e")]<- rowSums(subset_df_e) # I write a new column in the new DF with the rowSums of the estimates values, having calculated the new estimate
return(DF)
}
我缺少什么:一种在新数据框中写入选择相应估计中没有 0 值的列的 XXXmYY 值的结果的方法。如果估计中有一个或多个 0,那么我应该在计算中只包含一次 MoE 123。
实现这一目标的最干净的方法是什么?我看到我的斗争是同时处理几列,而 XXXeYY 列上的值决定了 XXXmYY 列的选择。
预期产出
row1: DF_to_write_on[paste0(New_column_name,"_m") <- sqrt(176^2 + 117^2+22^2 + 123^2)
row2: DF_to_write_on[paste0(New_column_name,"_m") <- sqrt(123^2)
B01001e1 B01001m1 B01001e2 B01001m2 B01001e3 B01001m3 B01001e4 B01001m4 B01001e5 B01001m5
15 566 176 371 117 14 22 0 123 0 123
20 0 123 0 123 0 123 0 123 0 123
数据
structure(list(B01001e1 = c(1691L, 2103L, 975L, 2404L, 866L,
2140L, 965L, 727L, 1602L, 1741L, 948L, 1771L, 1195L, 1072L, 566L,
1521L, 2950L, 770L, 1624L, 0L), B01001m1 = c(337L, 530L, 299L,
333L, 264L, 574L, 227L, 266L, 528L, 498L, 320L, 414L, 350L, 385L,
176L, 418L, 672L, 226L, 319L, 123L), B01001e2 = c(721L, 1191L,
487L, 1015L, 461L, 1059L, 485L, 346L, 777L, 857L, 390L, 809L,
599L, 601L, 371L, 783L, 1215L, 372L, 871L, 0L), B01001m2 = c(173L,
312L, 181L, 167L, 170L, 286L, 127L, 149L, 279L, 281L, 152L, 179L,
193L, 250L, 117L, 234L, 263L, 155L, 211L, 123L), B01001e3 = c(21L,
96L, 70L, 28L, 33L, 90L, 12L, 0L, 168L, 97L, 72L, 10L, 59L, 66L,
14L, 0L, 35L, 47L, 14L, 0L), B01001m3 = c(25L, 71L, 73L, 26L,
33L, 79L, 18L, 123L, 114L, 79L, 59L, 15L, 68L, 99L, 22L, 123L,
31L, 37L, 20L, 123L), B01001e4 = c(30L, 174L, 25L, 91L, 4L, 27L,
30L, 43L, 102L, 66L, 54L, 85L, 0L, 16L, 0L, 26L, 34L, 27L, 18L,
0L), B01001m4 = c(26L, 148L, 30L, 62L, 9L, 27L, 25L, 44L, 82L,
52L, 46L, 48L, 123L, 21L, 123L, 40L, 33L, 32L, 27L, 123L), B01001e5 = c(45L,
44L, 7L, 46L, 72L, 124L, 45L, 34L, 86L, 97L, 0L, 83L, 0L, 30L,
0L, 66L, 0L, 23L, 33L, 0L), B01001m5 = c(38L, 35L, 12L, 37L,
57L, 78L, 36L, 37L, 62L, 97L, 123L, 50L, 123L, 42L, 123L, 59L,
123L, 31L, 49L, 123L)), .Names = c("B01001e1", "B01001m1", "B01001e2",
"B01001m2", "B01001e3", "B01001m3", "B01001e4", "B01001m4", "B01001e5",
"B01001m5"), row.names = c(NA, 20L), class = "data.frame")