Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中同时检测多个变量中的尖锐突发_R_Dplyr_Tidyr - Fatal编程技术网

在R中同时检测多个变量中的尖锐突发

在R中同时检测多个变量中的尖锐突发,r,dplyr,tidyr,R,Dplyr,Tidyr,我尽量说清楚。 这里是数据 dt=structure(list(x1 = c(28.5, 25.5, 28, 27, 29), x2 = c(28.5, 25.5, 25, 25.5, 29), x3 = c(8, 5.5, 8.5, 7.5, 8), x4 = c(8.5, 6.5, 6.5, 5.5, 8), x5 = c(64L, 55L, 54L, 55L, 60L), x6 = c(63.5, 54.5, 53.5, 54.5, 60), x7 = c(1028L, 1010L,

我尽量说清楚。 这里是数据

dt=structure(list(x1 = c(28.5, 25.5, 28, 27, 29), x2 = c(28.5, 25.5, 
25, 25.5, 29), x3 = c(8, 5.5, 8.5, 7.5, 8), x4 = c(8.5, 6.5, 
6.5, 5.5, 8), x5 = c(64L, 55L, 54L, 55L, 60L), x6 = c(63.5, 54.5, 
53.5, 54.5, 60), x7 = c(1028L, 1010L, 1008L, 1010L, 1020L), x8 = c(1027L, 
1009L, 1007L, 1009L, 1020L)), class = "data.frame", row.names = c(NA, 
-5L))
我需要找到行,其中至少有2个以上变量
(x1-x8)
的值同时发生了急剧变化。例如,突然同时(这很重要)成长起来
x2、x4、x8

不管他们跳了多少,事实上是一个同时发生的(多个变量同时发生)和突然的事件。所以我们可以计算x2=
25.5-28.5=-3的差值(delta)

    x2   x4  x8
1 -3.0 -2.0 -18
2 -0.5  0.0  -2
3  0.5 -1.0   2
一般来说,每个变量前后的差值为偶数,x8急剧下降,但其他变量在其范围内,但有必要一次全部或至少两个变量。 这一点我们可以在最后一排看到

 4  3.5  2.5  11  changes last row
是否可以为我们看到极端增长的行设置标志=1

    x1   x2  x3  x4 x5   x6   x7   x8 flag
1 28.5 28.5 8.0 8.5 64 63.5 1028 1027    0
2 25.5 25.5 5.5 6.5 55 54.5 1010 1009    0
3 28.0 25.0 8.5 6.5 54 53.5 1008 1007    0
4 27.0 25.5 7.5 5.5 55 54.5 1010 1009    0
5 29.0 29.0 8.0 8.0 60 60.0 1020 1020    1

如果这是不可能的,那么是否可以设置,如果x1-x4中至少有2个变量在2mm上增长,同时变量x7-x8在10mm上增长,那么标记1?

以下代码使用基本R方法

(a) 。通过
apply()
命令计算每列的差异,然后

(b) 。统计每行是否有两个以上的变量具有大于3的绝对变化(阈值),如果是这种情况,则设置标志1,否则设置标志0

当然,您始终可以将阈值更改为另一个值,例如4或5

代码

threshold <- 3
flags <- dt %>% 
         apply(., 2, diff) %>% 
         apply(., 1,  
                  function(x) 
           ifelse(length(x[abs(x) > threshold]) > 1, 
                     1, 
                     0))
dt$flag <- c(0, flags)
dt
    x1   x2  x3  x4 x5   x6   x7   x8 flag
1 28.5 28.5 8.0 8.5 64 63.5 1028 1027    0
2 25.5 25.5 5.5 6.5 55 54.5 1010 1009    1
3 28.0 25.0 8.5 6.5 54 53.5 1008 1007    0
4 27.0 25.5 7.5 5.5 55 54.5 1010 1009    0
5 29.0 29.0 8.0 8.0 60 60.0 1020 1020    1