如何创建在特定条件下对另一列进行计数的列?右

2024-04-02

下面,数据已被重新调整,并列出了输入和预期输出。

Data

structure(list(record_id = c(110101, 110101, 110101, 110101, 
110101, 110101, 110101, 110101, 110101, 110101, 110101, 110101, 
110101, 110101, 110101, 110101, 110101, 110101, 110101, 110101, 
110101, 110101, 110101, 110101, 110101, 110101, 110101, 110101, 
110101, 110101, 110101, 110101, 110101, 110101, 110101, 110101, 
110101, 110101, 110101, 110101, 110101, 110101, 110101, 110101, 
110101, 110101, 110101, 110101, 110101, 110101, 110101, 110101, 
110101, 110101, 110101, 110101, 110101, 110101, 110101, 110101
), start = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 
31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 
47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59), stop = c(1, 
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 
52, 53, 54, 55, 56, 57, 58, 59, 60), `treatment (type)` = c(1, 
1, 1, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 3, 3, 0, 3, 3, 3, 
0, 2, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), n_interruption_periods = c(0, 
0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 
4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5), n_interruption_periods_3days = c(0, 
0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 
2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3), n_interruption_days_3days = c(0, 
0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 3, 4, 5, 6, 6, 6, 6, 6, 6, 6, 
6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7)), row.names = c(NA, 
-60L), class = c("tbl_df", "tbl", "data.frame"))

解释

Input start and stop是天数。日常治疗方法列于treatment,其中 0 = 没有治疗,即中断,1:3 是治疗 A/B/C。

Output基于treatment列,我想计算每天:

  1. n_interruption_periods:中断周期的总和/数量,与中断的持续时间无关
  2. n_interruption_periods_3days:总和/中断次数,条件是仅在持续时间 >= 3 天时才进行计数。少于 3 天的中断不值得关注
  3. n_interruption_days_3days:中断天数的累计总和/数量,其中中断仅从中断的第 3 天起计算。

Question我想创建一个脚本,根据以下内容自动计算上述输出变量treatment多变的。

希望你能帮忙

BW

响应操作

这是说明问题的部分数据:

structure(list(record_id = c(110001, 110002, 110002, 110002, 
110001), day_count = c(732, 0, 1, 2, 733), day_count_stop = c(733, 
1, 2, 3, 734), oac_class = c(0, 1, 1, 1, 1), n_interruption_periods = c(1, 
1, 0, 0, 1), n_interruption_periods_3days = c(1, 1, 0, 0, 1)), row.names = c(NA, 
-5L), groups = structure(list(record_id = c(110001, 110002), 
    .rows = structure(list(c(1L, 5L), 2:4), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

使用建议的代码,存在两个问题:

  1. 我相信生成的向量没有分配到正确的位置。在这里你可以看到 110002 第一个数据n_interruption_periods and n_interruption_periods_3days从 110001 个结果扩展而来。

  2. 当我尝试运行第三个向量时,收到此错误: while (any(d != 0)) { 中的错误:缺少 TRUE/FALSE 需要的值

BW


我想我们可以修改我在你上次写的函数post https://stackoverflow.com/a/64626161/10802499解决您的所有问题。考虑以下函数。

conditional_count <- function(x, n, pfill = function(p0) integer(length(p0)), ifill = seq_along, iend = 30L) {
  len <- length(x); out <- integer(len)
  p0 <- which(x == 0L)
  if (n > 1L)
    p0 <- Reduce(function(idx, i) {
      lidx <- idx - i + 1L
      idx <- idx[lidx > 0L]; lidx <- lidx[lidx > 0L]
      idx[x[lidx] == 0L]
    }, seq_len(n)[-1L], p0)
  if (length(p0) < 1L)
    return(out)
  ub <- pmin(c(tail(p0, -1L), len), p0 + iend - 1L)
  rl <- ub - p0 + 1L
  pfill <- pfill(p0)
  res <- unlist(lapply(seq_along(rl), function(i) ifill(integer(rl[[i]])) + pfill[[i]]))
  pos <- inverse.rle(list(lengths = rl, values = p0)) + unlist(lapply(rl, seq_len)) - 1L
  `[<-`(out, pos, res)
}

令 p0 为包含已识别的所有有效中断位置的向量。pfill and ifill是两个控制函数conditional_count. pfill控制如何填充向量p0中的每个位置;ifill控制如何填补两个有效中断之间的间隙。两个有效中断之间的最终序列将是ifill + pfill. iend控制最终序列的所需长度。见下图(x 是治疗(类型))

ifill controls the numbers  at *:             *****   *****   (iend = 5L for example)
pfill controls the numbers  at ?:             ?       ?
p0 identifies                   :             v       v
x looks like                    :   1    2    0  ...  0  ... 

以 n = 1 为例,你的最后一个问题简化为

conditional_count(x, 1L, function(p0) integer(length(p0)), seq_along, 30L)

ifill + pfill                              :       1 2 3 4 ...  1 2 3 4 ...
ifill is a sequence along the gap positions:       1 2 3 4 ...  1 2 3 4 ...
pfill is always 0 at all positions of p0   :       0            0       
p0 identifies                              :       v            v       
x looks like                               :   1 2 0 ........   0       

这个问题简化为

conditional_count(x, 1L, function(p0) cumsum(p0 - head(c(-1L, p0), -1L) > 1L), function(x) integer(length(x)), Inf)

ifill + pfill                                  :       1 1 1 ...     2 2 ...
ifill is always 0 along the gap positions      :       0 0 0 ...     0 0 ...  (iend = Inf means filling in a sequence until the end of the gap)
pfill increases 1 at each starting streak of 0s:       1             2
p0 identifies                                  :       v v v         v v
x looks like                                   :   1 2 0 0 0 ....... 0 0 ...

conditional_count(x, 1L, seq_along, function(x) integer(length(x)), Inf)

ifill + pfill                            :       1 2 3 ...     4 5 ...
ifill is always 0 along the gap positions:       0 0 0 ...     0 0 ...  (iend = Inf means filling in a sequence until the end of the gap)
pfill increases 1 at each 0              :       1 2 3         4 5
p0 identifies                            :       v v v         v v
x looks like                             :   1 2 0 0 0 ....... 0 0 ...

这个问题的完整脚本是

conditional_count <- function(x, n, pfill = function(p0) integer(length(p0)), ifill = seq_along, iend = 30L) {
  len <- length(x); out <- integer(len)
  p0 <- which(x == 0L)
  if (n > 1L)
    p0 <- Reduce(function(idx, i) {
      lidx <- idx - i + 1L
      idx <- idx[lidx > 0L]; lidx <- lidx[lidx > 0L]
      idx[x[lidx] == 0L]
    }, seq_len(n)[-1L], p0)
  if (length(p0) < 1L)
    return(out)
  ub <- pmin(c(tail(p0, -1L), len), p0 + iend - 1L)
  rl <- ub - p0 + 1L
  pfill <- pfill(p0)
  res <- unlist(lapply(seq_along(rl), function(i) ifill(integer(rl[[i]])) + pfill[[i]]))
  pos <- inverse.rle(list(lengths = rl, values = p0)) + unlist(lapply(rl, seq_len)) - 1L
  `[<-`(out, pos, res)
}

count_streak <- function(p0) cumsum(p0 - head(c(-1L, p0), -1L) > 1L)
integer_along <- function(x) integer(length(x))

df %>%
  mutate(
    n_interruption_periods = conditional_count(`treatment (type)`, 1L, count_streak, integer_along, Inf),
    n_interruption_periods_3days = conditional_count(`treatment (type)`, 3L, count_streak, integer_along, Inf),
    n_interruption_days_3days = conditional_count(`treatment (type)`, 3L, seq_along, integer_along, Inf)
  )

Output

   record_id start stop treatment (type) n_interruption_periods n_interruption_periods_3days n_interruption_days_3days
1     110101     0    1                1                      0                            0                         0
2     110101     1    2                1                      0                            0                         0
3     110101     2    3                1                      0                            0                         0
4     110101     3    4                0                      1                            0                         0
5     110101     4    5                0                      1                            0                         0
6     110101     5    6                0                      1                            1                         1
7     110101     6    7                0                      1                            1                         2
8     110101     7    8                2                      1                            1                         2
9     110101     8    9                2                      1                            1                         2
10    110101     9   10                2                      1                            1                         2
11    110101    10   11                0                      2                            1                         2
12    110101    11   12                0                      2                            1                         2
13    110101    12   13                0                      2                            2                         3
14    110101    13   14                0                      2                            2                         4
15    110101    14   15                0                      2                            2                         5
16    110101    15   16                0                      2                            2                         6
17    110101    16   17                3                      2                            2                         6
18    110101    17   18                3                      2                            2                         6
19    110101    18   19                0                      3                            2                         6
20    110101    19   20                3                      3                            2                         6
21    110101    20   21                3                      3                            2                         6
22    110101    21   22                3                      3                            2                         6
23    110101    22   23                0                      4                            2                         6
24    110101    23   24                2                      4                            2                         6
25    110101    24   25                2                      4                            2                         6
26    110101    25   26                2                      4                            2                         6
27    110101    26   27                0                      5                            2                         6
28    110101    27   28                0                      5                            2                         6
29    110101    28   29                0                      5                            3                         7
30    110101    29   30                1                      5                            3                         7
31    110101    30   31                1                      5                            3                         7
32    110101    31   32                1                      5                            3                         7
33    110101    32   33                1                      5                            3                         7
34    110101    33   34                1                      5                            3                         7
35    110101    34   35                1                      5                            3                         7
36    110101    35   36                1                      5                            3                         7
37    110101    36   37                1                      5                            3                         7
38    110101    37   38                1                      5                            3                         7
39    110101    38   39                1                      5                            3                         7
40    110101    39   40                1                      5                            3                         7
41    110101    40   41                1                      5                            3                         7
42    110101    41   42                1                      5                            3                         7
43    110101    42   43                1                      5                            3                         7
44    110101    43   44                1                      5                            3                         7
45    110101    44   45                1                      5                            3                         7
46    110101    45   46                1                      5                            3                         7
47    110101    46   47                1                      5                            3                         7
48    110101    47   48                1                      5                            3                         7
49    110101    48   49                1                      5                            3                         7
50    110101    49   50                1                      5                            3                         7
51    110101    50   51                1                      5                            3                         7
52    110101    51   52                1                      5                            3                         7
53    110101    52   53                1                      5                            3                         7
54    110101    53   54                1                      5                            3                         7
55    110101    54   55                1                      5                            3                         7
56    110101    55   56                1                      5                            3                         7
57    110101    56   57                1                      5                            3                         7
58    110101    57   58                1                      5                            3                         7
59    110101    58   59                1                      5                            3                         7
60    110101    59   60                1                      5                            3                         7
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何创建在特定条件下对另一列进行计数的列?右 的相关文章

  • 如何将闪亮 UI 输入框中的值传递回 R 脚本中的变量并运行它?

    我有以下代码source R我正打算逃离闪亮的 目前脚本中有硬编码值 例如 10000 55 15 200 等 以及这些值下面的一些矩阵相关元素 rnorm2 lt function n mean sd mean sd scale rnor
  • 通过 knit 和 igraph 在乳胶中绘制 tkplot

    这可能是一个疯狂的奇怪的梦 我梦想着我可以放一个tkplot from igraph在乳胶文档中通过knitr 我知道一辉对动画很了解 所以我想也许这是可能的 谷歌搜索没有显示我想要什么 所以这是一个无效的尝试 documentclass
  • 如何限制 viridis 色标的范围?

    我有两组数据 我想使用带有 viridis 色标的热图来呈现它们 对于第一个数据集 我的值范围从 0 到 1 2 我可以轻松看到我想要看到的差异 然而 我的第二个数据集有一些异常值 导致范围从 0 到 2 现在很难看出 0 和 1 之间有趣
  • 如何在 R 中导入并绘制三角形网格?

    我想在 R 中绘制我的模型输出 它是格式为的三角形网格 x1 y1 z1 x2 y2 z2 x3 y3 z3 value 每行代表一个三角形 我想用以下方法绘制这些三角形value作为规模 mymesh lt structure c 0 9
  • 如何在 R 中调整/控制树形图中的比例(使用“portfolio”库)?

    我正在使用 R 和 portfolio 库来构建树形图 比例默认为 1000 到 1000 例如 我需要它是 0到1000 我知道 map market 有一个 scale 参数 但我不知道要传递给它什么 围绕零的对称颜色映射被硬编码到ma
  • 使用名义变量删除 r 中的异常值

    比如说 我有三列 x lt c 10 1 6 50 x1 lt c 20 1 6 60 z lt c 1 2 3 4 5 6 7 8 检查 x 的异常值 bx lt boxplot x bx out 检查 x1 的异常值 bx1 lt bo
  • 计算一列中正数和负数的数量

    我想计算数据帧的一列中正值和负值的数量 我在 R 中该怎么做 例如 这里是数据框 logFC logCPM LR PValue FDR Bra15066 5 630822 5 184586 73 79927 8 647868e 18 4 0
  • 如何让 print() 将参数传递给 R 中用户定义的打印方法?

    我在 R 中定义了一个 S3 类 它需要自己的打印方法 当我创建这些对象的列表并打印它时 R 按其应有的方式对列表中的每个元素使用我的打印方法 我想对打印方法实际显示的数量进行一些控制 因此 我的类的 print 方法需要一些额外的参数 但
  • 使用 R Shiny 从 XLConnect 下载 Excel 文件

    有没有人尝试过使用 R Shiny 中的下载处理程序通过 XLConnect 下载新创建的 Excel 文件 在 ui R 中有一行不起眼的行 downloadButton downloadData Download 在 server R
  • 如何提取与 R 中主题 ID 列表匹配的行?

    我有一个包含许多主题 ID 的数据框 每个主题都有重复观察 我还有一个单独的数据框 其中只有一个主题 ID 列表 我想从更大的数据框中匹配和提取 如何以允许我引用不同数据帧中的SubjectID列表的方式编写代码 不确定我是否完全理解这个问
  • 基于服务器中的条件逻辑呈现闪亮的用户输入

    我正在尝试设置一个闪亮的导航栏面板页面 其中用户控制我根据一组单选按钮中所做的初始选择来显示更改 我直接在 ui 中渲染单选按钮 然后在 Server r 中的 观察到的 逻辑控制结构内构建条件控件 弹出错误是因为我的初始 if 语句计算结
  • ggplot2可以在一个图例中分别控制点大小和线大小(线宽)吗?

    一个使用的例子ggplot2绘制数据点组和连接每组均值的线 并使用相同的映射aes for shape并为linetype p lt ggplot mtcars aes gear mpg shape factor cyl linetype
  • 将 Instagram/youtube 嵌入 Shiny R 应用程序

    我想通过点击图表来播放 Instagram 或 Youtube 视频 例如显示异常值等 到目前为止 明确告诉 Shiny 视频内容是有效的 require shiny require ggplot2 data df lt data fram
  • 在 R 中创建一个运行计数变量?

    我有一个足球比赛结果的数据集 我希望通过创建一组类似于世界足球 Elo 公式的运行评级来学习 R 我遇到了麻烦 在 Excel 中看似简单的事情在 R 中并不完全直观 例如 4270 个观察中的前 15 个具有必要的变量 date t 1
  • 在shiny中过滤传单地图数据

    我在用传单地图设置这个闪亮的东西时遇到了麻烦 我的原帖 https stackoverflow com questions 50111566 applying leaflet map bounds to filter data within
  • R foreach问题(某些进程返回NULL)

    我遇到了问题foreach我正在 R 中使用的程序的一部分 该程序用于运行不同参数的模拟 然后将结果返回到单个列表 然后用于生成报告 当并非所有分配的模拟运行都在报告上实际可见时 就会出现问题 从各方面来看 似乎只有分配的运行的一个子集实际
  • 我无法下载 R 中的 reshape2 包 [关闭]

    Closed 这个问题是无法重现或由拼写错误引起 help closed questions 目前不接受答案 我在尝试安装 R 包时收到此响应 gt installed packages reshape2 Package LibPath V
  • R - Plm 和 lm - 固定效应

    我有一个平衡面板数据集 df 本质上由三个变量组成 A B and Y 对于一堆独特识别的区域来说 它会随着时间的推移而变化 我想运行一个回归 其中包括区域 下面等式中的区域 和时间 年份 固定效应 如果我没记错的话 我可以通过不同的方式来
  • 使用 pracma::findpeaks 识别持续峰值

    我的语法有问题peakpat内的选项findpeaks内的函数pramcaR 包 v 2 1 1 我使用的是 R 3 4 3 x64 Windows 我希望该函数能够识别可能有两个重复值的峰值 并且我相信该选项peakpat这就是我能做到的
  • 多功能测试仪替代 system.time

    我已经看到 我认为是这样 使用了类似于 system time 的函数 它可以同时评估多个函数的时间并输出一个输出 我不记得它是什么 并且用我正在使用的术语进行互联网搜索并没有得到我想要的响应 有人知道我正在谈论的功能的名称 位置吗 你想要

随机推荐

  • 动态数组占用的“真实”内存大小是多少?

    Example procedure Test var AText array of AnsiChar begin SetLength AText 7 end Question 的实际尺寸是多少AText占用内存 是7 其长度的基数大小 即7
  • PHP - session_unset 是否取消注册 $_SESSION 变量?

    Does session unset http php net manual en function session unset php取消注册所有 SESSION 变量 或者是否必须手动清除注册到 SESSION 数组中的每个变量unse
  • 使用命令式绑定时的 Azure Functions 测试

    到目前为止 我已经能够为 Azure Functions 设置单元测试 并且效果很好 然而 对于我当前的项目 我需要使用动态或命令式绑定 https learn microsoft com en us azure azure functio
  • SQL Server Management Studio 中的宏

    有没有办法在SSMS中实现文本编辑宏 我会 例如喜欢将代码转换为如下所示 但只需按键 而不是冗长的正则表达式搜索和替换 This INSERT INTO TABLE fieldOne fieldTwo VALUES
  • Learning Swift:顶层不允许使用表达式

    我正在学习斯威夫特 我遇到了一个无法解决的问题 import UIKit func helloword str String print str helloword say I use helloword say 但 Xcode 告诉我错误
  • “int '对象不可下标”

    我开始学习GEKKO 现在 我正在解决一个 knapsak 问题来学习 但是这次我收到错误 int object is not subscriptable 你能看一下这段代码吗 问题的根源是什么 我应该如何定义 1 10 矩阵 from g
  • SWI-Prolog - 显示长列表

    我正在使用 SWI Prolog 我正在尝试打印一个列表 但如果该列表有超过 9 个项目 它看起来像那样 1 15 8 22 5 19 12 25 3 有没有办法显示整个列表 看一下 http www swi prolog org FAQ
  • 在 Yii 框架中配置数据库连接

    在Yii框架的main php文件中 有一些配置选项 这就是mysql的设置方式 db gt array connectionString gt mysql host localhost dbname testdrive emulatePr
  • Pylint 警告:可能存在不平衡的元组按顺序解包

    我有一段Python代码 def func1 a set b join map str list a return b def func2 d 1 e 2 return func1 d e def main a b c d func2 if
  • Swift 中具有共享 NSUserDefaults 的 KVO

    我在通过通信 NSUserDefaults 更改在主机应用程序及其扩展之间进行通信时遇到问题 我初始化了NSUserDefaults using init suiteName 添加 KVO 观察者使用addObserver 方法并覆盖该方法
  • Lombok 未在 Netbeans 项目中工作

    我想在项目中使用Lombok来使用 Getter和 Setter 我包括使用 Maven
  • 显示图像的片段中的内存问题

    我正在使用片段来显示图像 页面 我有一个活动 主要 其中包含所有片段 package com example hscroll demo import android os Bundle import android preference P
  • 为 POCO 实施 IEquatable

    我注意到 EF 的 DbSet Add 非常慢 谷歌搜索了一下 找到了一个 SO 答案 承诺性能提升高达 180 倍 https stackoverflow com a 7052504 141172 https stackoverflow
  • 计算 SQL 中特定事件之前和之后的事件数量?

    我有一个包含日期和事件的表 有一个名为 A 的事件 我想知道 Sql Bigquery 中事件 A 之前和之后发生了多少个事件 例如 User Date Events 123 2018 02 13 D 123 2018 02 12 B 12
  • 从网络数据抓取类返回数据?

    我正在尝试创建一个类 它可以让我从网络服务获取请求的数据 我被困在如何返回值上 FooClass m DataGrabber is the class which is supposed to get values dataGrabber
  • R:使用矢量化按间隔分配值

    让我们有一个数字向量 a lt round runif 20 1 5 0 1 3 5 4 2 1 2 3 4 5 2 我需要使用如下表为这些数字分配值 1 to 2 assign A 3 to 4 assign B 5 assign C 这
  • Ruby Mixins 和实例变量

    是否有将参数传递给混合方法的最佳实践方法 使用 mixin 的类可以设置混合方法期望的实例变量 或者可以将所有必要的参数作为参数传递给混合方法 背景是我们有一个 Rails 控制器来发布内容 但其他控制器甚至模型都需要能够 充当发布者 所以
  • 错误“来源:系统进程已退出,因此请求的信息不可用”

    它在我的电脑上可以工作 但是当我放入另一台机器时 我收到错误 源 系统进程已退出 因此请求的信息不可用 并且 exe 没有出来 有哪位有经验的兄弟可以帮忙吗 赞赏 p New Process With p EnableRaisingEven
  • GooglePlayServices Admob 问题:“无法加载广告:0”

    我对新的 admob 有疑问 这是我的代码 尝试在我的主要活动中创建和加载广告 private void createAndLoadAd String adUnitID RelativeLayout rlRoot View upperVie
  • 如何创建在特定条件下对另一列进行计数的列?右

    下面 数据已被重新调整 并列出了输入和预期输出 Data structure list record id c 110101 110101 110101 110101 110101 110101 110101 110101 110101 1