0

我的数据框如下所示:

View(df)
Product     Value
  a           2
  b           4 
  c           3
  d           10
  e           15
  f           5
  g           6
  h           4
  i           50
  j           20
  k           35
  l           25
  m           4
  n           6
  o           30
  p           4
  q           40
  r           5
  s           3
  t           40

我想找到 9 种最昂贵的产品并总结其余的。它应该如下所示:

Product     Value 
  d           10
  e           15
  i           50
  j           20
  k           35
  l           25
  o           30
  q           40
  t           40
 rest         46

余数是其他 11 个产品的总和。我试过了summaries,但没有用:

new <- df %>%
  group_by(Product)%>%
summarise((Value > 10) = sum(Value)) %>%
  ungroup()
4

3 回答 3

2

We can use dplyr::row_number to effectively rank the observations after using arrange to order the data by Value. Then, we augment the Product column so that any values that aren't in the top 9 are coded as Rest. Finally, we group by the updated Product and take the sum using summarise

dat %>%
    arrange(desc(Value)) %>%
    mutate(RowNum = row_number(),
           Product = ifelse(RowNum <= 9, Product, 'Rest')) %>%
    group_by(Product) %>%
    summarise(Value = sum(Value))

# A tibble: 10 × 2
   Product Value
     <chr> <int>
1        d    10
2        e    15
3        i    50
4        j    20
5        k    35
6        l    25
7        o    30
8        q    40
9     Rest    46
10       t    40

data

dat <- structure(list(Product = c("a", "b", "c", "d", "e", "f", "g", 
"h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t"
), Value = c(2L, 4L, 3L, 10L, 15L, 5L, 6L, 4L, 50L, 20L, 35L, 
25L, 4L, 6L, 30L, 4L, 40L, 5L, 3L, 40L)), .Names = c("Product", 
"Value"), class = "data.frame", row.names = c(NA, -20L))
于 2017-03-04T01:54:02.443 回答
1

另一种方法dplyr是使用do. 代码变得有点难以阅读,因为你需要使用.$,但你可以避免ifelse/if_else。按 排列顺序后Value,您可以创建两个向量。一个具有前九个产品名称和“其余”。另一个与前九个值和其他值的值之和。您直接使用创建数据框do

df %>%
arrange(desc(Value)) %>%
do(data.frame(Product = c(as.character(.$Product[1:9]), "Rest"),
              Value = c(.$Value[1:9], sum(.$Value[10:length(.$Value)]))))

#   Product Value
#1        i    50
#2        q    40
#3        t    40
#4        k    35
#5        o    30
#6        l    25
#7        j    20
#8        e    15
#9        d    10
#10    Rest    46
于 2017-03-04T03:23:35.583 回答
1

这是使用的一个选项data.table

library(data.table)
setDT(df)[, i1 := .I][order(desc(Value))
          ][-(seq_len(9)), Product := 'rest'
           ][, .(Value = sum(Value), i1=i1[1L]), Product
           ][order(Product=='rest', i1)][, i1 := NULL][]
#    Product Value
#1:       d    10
#2:       e    15
#3:       i    50
#4:       j    20
#5:       k    35
#6:       l    25
#7:       o    30
#8:       q    40
#9:       t    40
#10:   rest    46
于 2017-03-04T05:49:45.273 回答