dplyr подход для таких как Excel - PullRequest
0 голосов
/ 27 марта 2019

у меня есть ключ в таблице A, а в таблице B у меня есть ключ и номер.Как я могу достичь формулы Excel Sumifs (числовой, tableB.key, tableA.key, tableA.key, 1) с dplyr без объединения двух таблиц

я уже пробовал summarise_if в mutate

mutate(newColumn = summarise_if(tableB, .predicate = tableB$Key == .$Key, .funs = sum(tableB$numeric)))

but i get this error

In tableB$Key == .$Key:
 longer object length is not a multiple of shorter object length
tableA         tableB
key             key numeric 
1               1   10
2               1   30
3
4



Expected
key  newColumn
1    40
2
3
4

1 Ответ

0 голосов
/ 27 марта 2019

вы можете попробовать

library(tidyverse)

tableA <- tibble(key = c(1, 2, 3, 4))
tableB <- tibble(key = c(1, 1, 2, 2),
                 numeric = c(10, 30, 10, 15))

(function(){

  tmpDF <- tableB %>%
    filter(key %in% tableA$key) %>%
    group_by(key) %>%
    summarise(newColumn = sum(numeric))

  tableA %>%
    mutate(new = ifelse(key == tmpDF$key, tmpDF$newColumn, 0)
    )

})()

, что дает

# A tibble: 4 x 2
#    key   new
#  <dbl> <dbl>
#     1    40
#     2    25
#     3     0
#     4     0
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...