首页 > 解决方案 > 在数据框列中生成范围

问题描述

我在 R studio 中生成一个数据框。有 4 列 ITA、概率、累积概率和范围

我的代码运行良好

InterArrivalInput <- list(InterArrival = c(1,2,3,4),
                      Probability = c(0.25,0.40,0.20,0.15))
countDF <- function(input) {


Cumulative <- cumsum(input$Probability)
Range <- (Cumulative * 100) 

df <- data.frame(InterArrivals = input$InterArrival,
               Probability = input$Probability,
               Cumulative = Cumulative,
               Range = Range
}

目前其计算范围为例如25,累积概率为 0.25。

Commulative | Range
0.25        | 25
0.65        | 55

我如何生成范围列作为

Commulative | Range
0.25        | 0 - 25
0.65        | 26 - 55

我开始学习R语言。不知道它是否可能。谢谢

标签: rdataframe

解决方案


Range <- c(25, 55)
mapply(paste, c(1, 1 + head(Range, n=-1)), Range, sep = " - ")
# [1] "1 - 25"  "26 - 55"

head(..., n=-1)正在检索除最后一个条目之外的所有1内容(因此head(..., n=-3)检索除最后 3 个条目之外的所有内容)。

mapply是应用函数的“压缩”版本,如果我展开它并显示函数(第一个参数)是如何被重复调用的,它看起来像这样:

c(1, 1 + head(Range, n=-1))
# [1]  1 26
Range
# [1] 25 55
paste(1, 25, sep = " - ")
# [1] "1 - 25"
paste(26, 55, sep = " - ")
# [1] "26 - 55"

推荐阅读