【问题标题】:IF(SUMPRODUCT(MAX formula using RIF(SUMPRODUCT(MAX 公式使用 R
【发布时间】:2020-11-08 03:29:33
【问题描述】:

我在 R 中有下表,并希望生成一个附加列,在 Excel 中将使用以下公式执行:

=IF(B2=0,SUMPRODUCT(MAX(($A$2:$A$11=A2)($C$2:$C$11=C2)($B$2:$B $11))),B2)

这个公式说: 如果单价 = 0,则: 将所有其他销售的最高单价返回到 同一个客户和 同一个项目。

如果单价不为零,则返回相同的单价。

相对于 A:C 列所需的输出是:

  • 单价2
  • 2
  • 5
  • 1
  • 2
  • 4
  • 5
  • 2
  • 3
  • 7
  • 6
structure(list(customer = c("John", "Atticus", "Sally", "Bridget", 
"John", "Atticus", "Bridget", "Atticus", "Crystal", "Henry"), 
    `unit price` = c(2, 0, 1, 0, 4, 5, 2, 3, 7, 6), item = c("x", 
    "x", "y", "y", "y", "x", "y", "x", "x", "x")), class = c("spec_tbl_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L), spec = structure(list(
    cols = list(customer = structure(list(), class = c("collector_character", 
    "collector")), `unit price` = structure(list(), class = c("collector_double", 
    "collector")), item = structure(list(), class = c("collector_character", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
    "collector")), skip = 1), class = "col_spec"))

# A tibble: 10 x 3
   customer `unit price` item 
   <chr>           <dbl> <chr>
 1 John                2 x    
 2 Atticus             0 x    
 3 Sally               1 y    
 4 Bridget             0 y    
 5 John                4 y    
 6 Atticus             5 x    
 7 Bridget             2 y    
 8 Atticus             3 x    
 9 Crystal             7 x    
10 Henry               6 x   

【问题讨论】:

  • 请提供可用数据(而不是假定转录服务)。
  • 请使用dput 或我们可以复制和使用的东西添加数据。还显示共享数据的预期输出。了解how to ask a good questionhow to give a reproducible example
  • 对于写得不好的问题,我深表歉意。我对其进行了编辑以包含可重现的数据和所需的输出。希望这是正确的格式。谢谢

标签: r if-statement excel-formula max sumproduct


【解决方案1】:

使用group_by 考虑基于每个客户的计算,然后使用mutate 添加列:

library(dplyr)
DF %>% 
  group_by(customer) %>%
  mutate(unit_price2 = if_else(`unit price` == 0, max(`unit price`), `unit price`))

【讨论】:

    猜你喜欢
    • 2022-12-11
    • 2014-01-27
    • 2018-12-02
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2023-03-29
    相关资源
    最近更新 更多