2016-11-22 48 views
0

我需要一個新的行添加到每個ID組,其中關鍵字=「n」和值是總 - A + B添加缺少的小計爲每個組使用dplyr

x <- data_frame(id = c(1,1,1,2,2,2,2), 
       key = c("a","b","total","a","x","b","total"), 
       value = c(1,2,10,4,1,3,12)) 

# A tibble: 7 × 3 
    id key value 
    <dbl> <chr> <dbl> 
1  1  a  1 
2  1  b  2 
3  1 total 10 
4  2  a  4 
5  2  x  1 
6  2  b  3 
7  2 total 12 

在這個例子中,所述新行應

 1  n  7 
     2  n  5 

我試圖獲得A + b小計和加入該總數量,以獲得差異,但採用九個dplyr動詞後,我似乎在錯誤的方向走了。謝謝。

回答

3

這不是一個連接,它只是在結合新行:

x %>% group_by(id) %>% 
    summarize(
     value = sum(value[key == 'total']) - sum(value[key %in% c('a', 'b')]), 
     key = 'n' 
    ) %>% 
    bind_rows(x) %>% 
    select(id, key, value) %>% # back to original column order 
    arrange(id, key)   # and a start a row order 
# # A tibble: 9 × 3 
#  id key value 
# <dbl> <chr> <dbl> 
# 1  1  a  1 
# 2  1  b  2 
# 3  1  n  7 
# 4  1 total 10 
# 5  2  a  4 
# 6  2  b  3 
# 7  2  n  5 
# 8  2 total 12 
# 9  2  x  1 
1

下面是使用data.table,結合排在格里的回答道:

library(data.table) 
setDT(x) 

dcast(x, id ~ key)[, .(id, key = "n", value = total - a - b)][, rbind(.SD, x)][order(id)] 

    id key value 
1: 1  n  7 
2: 1  a  1 
3: 1  b  2 
4: 1 total 10 
5: 2  n  5 
6: 2  a  4 
7: 2  x  1 
8: 2  b  3 
9: 2 total 12