【问题标题】:R - create dataframe by conditionsR - 按条件创建数据框
【发布时间】:2020-05-22 17:02:08
【问题描述】:

我有两个简单的数据框

a <- data.frame(units = 4512)
b <- data.frame(units = 6200)

还有一个条件简单的数据框

price <-
  data.frame(
    from = c(1, 3000, 6000, 10001),
    to = c(3001, 6001, 10001, 999999),
    price = c(25, 22, 20, 17)
  )

我想要实现的是这个。

a_result <-
  data.frame(
    units = c(3000, 1512),
    price = c(25, 22)
  )

b_result <-
  data.frame(
    units = c(3000, 3000, 200),
    price = c(25, 22, 20)
  )

价格数据框价格中有定义的价格。根据结果​​数据帧中 a、b 行中的单位值,应该用最大可能的单位“填充”。

如您所见,数据框中的单位值为 4512,在 1-3000 类别中我们应该填充 3000 个单位,但在 3000-6000 类别中我们只能填充 1512 个单位(3000 个单位已经填充到较低的类别中)。

但我正在寻找一些功能或简单的 if else 语句。我曾经手动解决这个问题,但这需要大量重复和丑陋的代码。

【问题讨论】:

    标签: r dataframe if-statement


    【解决方案1】:

    试试这样的。当然,您可以通过使用不同格式的输入来简化此操作,但我认为您这样做是有充分理由的 :-)

    library(dplyr)
    
    
    f <- function(df, price){
      merge(df, price, all=TRUE) %>%  # Join the number of units on to *each* row of the price table
        mutate(
          interval_length = pmax(pmin(units, to) - from, 0), # Calculate the overlap between each interval and your value
        ) %>%
        filter(
          interval_length > 0  # Remove any prices that aren't applicable
        )
    }
    
    f(a, price)  # Make the output table for one input
    
    lapply(list(a,b), f, price)  # Make the output table for all inputs
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      相关资源
      最近更新 更多