【问题标题】:(Excel) function to return specific value from a table based on conditions(Excel) 函数根据条件从表中返回特定值
【发布时间】:2019-09-12 08:43:01
【问题描述】:

我有以下数据:

store   location   mass   target
1       1 (Ams)    45     ?
2       5 (Ber)    500    ?
3       8 (Mar)    1003   ?

在最后一列 target 我想从表中获取一个值:

              location 
 mass range    1       5     8 
 0 - 350       3       4     5
 > 351         6       7     8

所以目标列的前三行应该包含值 3、7、8。

我尝试使用函数 INDEX() 但没有成功。如果有人知道如何在 R 或 PowerBI 中执行此操作,那也会对我有所帮助。谢谢!

在 R 中,该示例可通过以下方式重现:

structure(list(Store = 1:3, Location = structure(c(2L, 3L, 1L
), .Label = c("08-Mar", "1 Ams", "5 Ber"), class = "factor"), 
Mass = c(1000L, 800L, 500L)), class = "data.frame", row.names = c(NA, 
                                                                  -3L))

structure(list(X = structure(1:2, .Label = c("0 - 350", "351 - 1000"
), class = "factor"), X1 = c(3L, 6L), X5 = c(4L, 7L), X8 = c(5L, 
8L)), class = "data.frame", row.names = c(NA, -2L))

【问题讨论】:

  • 对于 R,您能否通过使用 dput 添加数据来使这篇文章可重现?

标签: r excel powerbi


【解决方案1】:

修改你的表 2 然后你可以使用 INDEXMATCH 函数如下

【讨论】:

    【解决方案2】:

    在 R 中,我们需要一些预处理才能真正合并两个表,因为数据不是标准格式。假设这两个表分别称为df1df2,我们将separate 的数据放到df1 中的Locationdf2 中的X 的不同列中。我们还在df1 中添加了额外的"X" 字符,使其与df2 的列名匹配。我们在df2中使用gather引入长格式数据,并使用fuzzy_left_join按数字范围合并。

    library(fuzzyjoin)
    library(tidyverse)
    
    df1 %>%
      separate(Location, into = c("Loc1", "Loc2"), sep = "\\s+|-", convert = TRUE) %>%
      mutate(Loc1 = paste0("X", Loc1)) %>%
      fuzzy_left_join(df2 %>%
                    separate(X, into = c("start", "end"), convert = TRUE) %>%
                    gather(key, Target, starts_with("X")),
              by = c("Loc1" = "key", "Mass" = "start", "Mass" = "end"), 
              match_fun = list(`==`, `>=`, `<=`))
    
    #  Store Loc1 Loc2 Mass start  end key Target
    #1     1   X1  Ams 1000   351 1000  X1      6
    #2     2   X5  Ber  800   351 1000  X5      7
    #3     3   X8  Mar   45     0  350  X8      5
    

    数据

    df1 <- structure(list(Store = 1:3, Location = structure(c(2L, 3L, 1L
    ), .Label = c("08-Mar", "1 Ams", "5 Ber"), class = "factor"), 
    Mass = c(1000, 800, 45)), class = "data.frame", row.names = c(NA, -3L))
    
    df2 <- structure(list(X = structure(1:2, .Label = c("0 - 350", "351 - 1000"
    ), class = "factor"), X1 = c(3L, 6L), X5 = c(4L, 7L), X8 = c(5L, 
    8L)), class = "data.frame", row.names = c(NA, -2L))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多