r - 等到值改变进行计算
问题描述
我有以下数据框:
time <- c(1,2,3,4,5,6,7,8,9,10,11,12)
threshold <- c(1,1,1,0,0,2,2,1,1,2,2,0)
value <- c(5,3,2,4,6,9,1,10,3,5,2,4)
df <- data.frame(time, threshold, value)
阈值变量背后的逻辑是当有 1 时:存储第一个值 (5) 并在阈值变化时减去该数字 (4)。在“1”的第一个阈值期间,计算将是 5 - 4 = 1,应在时间 t=4 将其存储在新列中。
阈值“0”表示不计算。
阈值“2”表示正好与“1”相反,其中初始值 9 减去 10。
有没有办法计算在 R 中执行这个计算?
解决方案
如果您使用该rle
函数,您可以关注存在阈值变化的行。然后,对齐要减去的值并将阈值转换为控制减法感觉的因素。
#Select only rows with a threshold change,
# based on https://stackoverflow.com/a/27482738/14027775
compact_threshold <- rle(df$threshold)
row_ids <- cumsum(c(1, compact_threshold$lengths[-length(compact_threshold$lengths)]))
#Transform thresholds to a factor
# if the row is in a threshold change
df$subFactor <- df$threshold
df$subFactor[-row_ids] <- NA
df$subFactor[df$subFactor==0] <- NA
df$subFactor[df$subFactor==2] <- -1
#Align each value with the one
# corresponding to the next threshold change
df$value2 <- NA
df$value2[row_ids] <- c(df$value[row_ids][-1], NA)
df$calculation <- (df$value-df$value2)*df$subFactor
#Shift results to the next threshold
df$calculation[row_ids] <- c(NA, df$calculation[row_ids][-length(row_ids)])
df <- df[,c("time", "threshold", "value", "calculation")]
df
# time threshold value calculation
#1 1 1 5 NA
#2 2 1 3 NA
#3 3 1 2 NA
#4 4 0 4 1
#5 5 0 6 NA
#6 6 2 9 NA
#7 7 2 1 NA
#8 8 1 10 1
#9 9 1 3 NA
#10 10 2 5 5
#11 11 2 2 NA
#12 12 0 1 -4
原始数据
#Data
time <- c(1,2,3,4,5,6,7,8,9,10,11,12)
threshold <- c(1,1,1,0,0,2,2,1,1,2,2,0)
value <- c(5,3,2,4,6,9,1,10,3,5,2,1)
df <- data.frame(time, threshold, value)
df
# time threshold value
#1 1 1 5
#2 2 1 3
#3 3 1 2
#4 4 0 4
#5 5 0 6
#6 6 2 9
#7 7 2 1
#8 8 1 10
#9 9 1 3
#10 10 2 5
#11 11 2 2
#12 12 0 1
推荐阅读
- arrays - C(gcc)中未知数组大小typedef到已知数组大小类型的惊人完成
- python - iretate df 中的列并用 pandas 中的一列计算欧几里得距离?
- java - xades4j 生成的文件无效(XAdES-BES 封装)
- azure - 将消息放入服务总线中的队列后未触发 Azure 函数
- xaml - 无法将颜色绑定到 LinearGradientBrush
- typescript - 为什么我在运行 Oak 时收到此消息(错误:TS2376)?正文中的错误详细信息
- python - 如何点击段落中的特定文本?
- javascript - 如何尝试/捕获子函数?
- typescript - Cypress 7.2.0 升级,导入不是模块
- javascript - 如何将函数的返回值存储在reactJS中的变量中