cumsum и продукт на основе уникального идентификатора - PullRequest
1 голос
/ 14 июля 2020

Я работаю над большим набором данных для вычисления единственного значения в R. Я считаю, что продукт CUMSUM и cum подойдет. Но я не знаю, как

county_id <- c(1,1,1,1,2,2,2,3,3)
res <- c(2,3,2,4,2,4,3,3,2)

Мне нужна функция, которая может просто дать мне одно значение, как показано ниже, для каждого county_id, тогда мне нужна общая сумма. Например, для county_id = 1 сумма res вычисляется вручную как

2(3+2+4)+3(2+4)+2(4)

для county_id = 2 сумма для res вычисляется вручную как

2(4+3)+4(3)

для county_id = 3 общая для res вычисляется вручную как

3(2)

Затем он суммирует все это в одну переменную

44+26+6=76

NB мой county_id запускается с 1:47, и каждый county_id может иметь до 200 res

Спасибо

Ответы [ 4 ]

1 голос
/ 14 июля 2020

Вы можете использовать aggregate с cumsum, например:

x <- aggregate(res, list(county_id)
 , function(x) sum(rev(cumsum(rev(x[-1])))*x[-length(x)]))
#Group.1  x
#1       1 44
#2       2 26
#3       3  6
sum(x[,2])
#[1] 76
1 голос
/ 14 июля 2020

Вы можете суммировать произведение попарных комбинаций:

library(dplyr)

dat %>%
  group_by(county_id) %>%
  summarise(x = sum(combn(res, 2, FUN = prod)))

# A tibble: 3 x 2
  county_id     x
      <dbl> <dbl>
1         1    44
2         2    26
3         3     6

База R:

aggregate(res ~ county_id, dat, FUN = function(x) sum(combn(x, 2, FUN = prod)))
0 голосов
/ 21 июля 2020
Another option is to use SPSS syntax

// You need to count the number of variables with valid responses
count x1=var1 to var4(1 thr hi).
execute.

// 1st thing is to declare a variable that will hold your cumulative sum
// Declare your variables in terms of a vector
//You then loop twice. The 1st loop being from the 1st variable to the number of 
//variables with data (x1). The 2nd loop will be from the 1st variable to the    `
//variable in (1st loop-1) for all variables with data.`
//Lastly you need to get a cumulative sum based on your formulae
// This syntax can be replicated in other software.

compute index1=0.
vector x=var1 to var4.
loop #i=1 to x1.
loop #j=1 to #i-1 if not missing(x(#i)).
compute index1=index1+(x(#j)*sum(x(#i))).
end loop.
end loop.
execute.
0 голосов
/ 14 июля 2020

Вот один из способов сделать это с помощью функций tidyverse.

Для каждого county_id мы умножаем текущее значение res на значение sum из res после него.

library(dplyr)
library(purrr)

df1 <- df %>%
         group_by(county_id) %>%
         summarise(result = sum(map_dbl(row_number(), 
                           ~res[.x] * sum(res[(.x + 1):n()])), na.rm = TRUE))

df1
#  county_id result
#      <dbl>  <dbl>
#1         1     44
#2         2     26
#3         3      6

Чтобы получить общее количество sum, вы можете сделать:

sum(df1$result)
#[1] 76

данные

county_id <- c(1,1,1,1,2,2,2,3,3)
res <- c(2,3,2,4,2,4,3,3,2)
df <- data.frame(county_id, res)
...