使用R删除时间序列中连续零值之前的行

如何解决使用R删除时间序列中连续零值之前的行

我有一个时间序列作为数据帧,如下所示:

date          country      value       id
1/1/2020       A            .2         Cv
1/2/2020       A             0         Cv
1/3/2020       A             0         Cv 
.....         ...           ....       ...
2/10/2020      A              2        ...
2/11/2020      A              0        Cv
3/11/2020.     A              0        Cv
4/11/2020      A              0        Cv
5/11/2020      A              3        Cv
6/11/2020      A              4        Cv
7/11/2020      A              6        Cv
8/11/2020      A              7        Cv

我想删除数据帧中最后一个零序列之前的所有值: 我尝试了以下代码:

test <- ddply(df,.(id),function(x){
  temp_country_data <- ddply(x,.(country),function(y){
    temp_data <- data.frame(y) %>% arrange(date) %>% group_by("id","country") 
dat<-temp_data
    ToRemove <- apply(dat,2,function(colmn) {
      row.zeros <- which(colmn == 0) # rows with zeros
      if(length(row.zeros) > 0) { # if we found any
        # which of them is the last double
        last.doubles <- max(which(diff(row.zeros) == 1))
        leftof.last.doubles <- "if"(length(last.doubles) > 0,# if double exists1:(row.zeros[last.doubles]-1),# all rows before
                                    NULL) # else nothing
        # remove rows with single zeros and all rows before double consecutive 
        unique(c(row.zeros,leftof.last.doubles)) }
      temp_data<-dat[-unlist(ToRemove),]
    temp_data = temp_data[,c("date","id","country","value")]
    temp_data
  },.parallel = T)
  temp_country_data
},.progress = 'text')

但是,它仅删除了我不想要的零值。 我希望输出如下所示:另外,我想在最后的零序列之后间隔2天:

7/11/2020      A              6        Cv
8/11/2020      A              7        Cv

......

我也尝试过,但是仍然没有得到结果:

test3 <- ddply(df,"country") 
    temp_data<- temp_data%>% mutate(flag_0 = ifelse(value == 0,1,0),flag_0_cum = cumsum(flag_0)) %>% 
      filter(flag_0_cum == max(flag_0_cum)) %>% 
      filter(round(value,3) != 0) %>% 
      select(-flag_0,-flag_0_cum) %>%
      slice(3:n())
    temp_data = temp_data[,"short_id","raw_de")]
    library(lubridate)
    
    temp_data <- temp_data %>% 
      group_by(country,id) %>%                          
      mutate(DATE = ymd(date),day_flag = if_else(DATE == (lag(DATE) + days(1)),0))

temp_data<- temp_data %>% filter(!is.na(day_flag))
temp_data<- temp_data %>% 
  mutate(flag_0 = ifelse(day_flag == 0,flag_0_cum = cumsum(flag_0)) %>% 
  filter(flag_0_cum == max(flag_0_cum)) %>% 
  filter(day_flag != 0) %>% 
  select(-flag_0,-flag_0_cum) %>%
  slice(3:n())

   temp_data
  },.progress = 'text')

我在数据框中添加了另一列,以将连续的行标记为1,而不将连续的行标记为0。

请让我知道问题出在哪里。

解决方法

一种方法是用累积总和来标记零的出现(每次出现新的零时,标记都会加1),并仅保留包含最后零和所有后续非零值的最后一组。然后我们可以删除零本身和前两行:

library(dplyr) 

df <- data.frame(date = seq.Date(from = as.Date("2020-11-01"),to = as.Date("2020-11-08"),by = "day"),country = "A",value = c(2,3,4,6,7),id = "Cv")

df %>% 
  mutate(flag_0 = ifelse(round(value,4) == 0,1,0),flag_0_cum = cumsum(flag_0)) %>% 
  filter(flag_0_cum == max(flag_0_cum)) %>% 
  filter(round(value,4) != 0) %>% 
  select(-flag_0,-flag_0_cum) %>%
  slice(3:n())
,

您可以使用print (df1) Month_Year Hotel_id 0 2016-04-30 2400133 1 2016-05-31 2400133 2 2016-06-30 2400133 3 2016-07-31 2400133 4 2016-08-31 2400133 5 2016-09-30 2400133 6 2016-10-31 2400133 7 2016-11-30 2400133 8 2016-12-31 2400133 9 2017-01-31 2400133 10 2017-02-28 2400133 11 2017-03-31 2400133 12 2017-04-30 2400133 13 2017-05-31 2400133 14 2015-06-30 2400178 15 2015-07-31 2400178 16 2015-08-31 2400178 17 2015-09-30 2400178 18 2015-10-31 2400178 19 2015-11-30 2400178 20 2015-12-31 2400178 21 2016-01-31 2400178 22 2016-02-29 2400178 23 2016-03-31 2400178 24 2016-04-30 2400178 25 2016-05-31 2400178 26 2016-06-30 2400178 27 2016-07-31 2400178 28 2016-08-31 2400178 29 2016-09-30 2400178 30 2016-10-31 2400178 31 2016-11-30 2400178 32 2016-12-31 2400178 33 2017-01-31 2400178 34 2017-02-28 2400178 35 2017-03-31 2400178 36 2017-04-30 2400178 37 2017-05-31 2400178 38 2017-06-30 2400178 39 2017-07-31 2400178 40 2017-08-31 2400178 41 2017-09-30 2400178 42 2017-10-31 2400178 43 2017-11-30 2400178 44 2017-12-31 2400178 45 2018-01-31 2400178 46 2018-02-28 2400178 47 2018-03-31 2400178 48 2018-04-30 2400178 49 2015-05-31 2400614 50 2015-06-30 2400614 51 2015-07-31 2400614 52 2015-08-31 2400614 53 2015-09-30 2400614 54 2015-10-31 2400614 55 2015-11-30 2400614 56 2015-12-31 2400614 57 2016-01-31 2400614 58 2016-02-29 2400614 59 2016-03-31 2400614 标识零,并使用diff创建新索引cumsum。然后排除零行,并在ix中将值为head的{​​{1}}应用于2,以得到零后的前两行。最后by

rbind

数据:

DF1 <- as.data.frame(cbind(DF,ix=cumsum(c(-1,diff(DF$value == 0)) %in% 1)))
DF1 <- DF1[DF1$value != 0,]
res <- do.call(rbind,by(DF1,DF1$ix,head,2))
head(res)
#           date country value id ix
# 0   2020-01-01       A   3.0 Cv  0
# 1.3 2020-01-03       A   3.0 Cv  1
# 1.4 2020-01-04       A   2.0 Cv  1
# 2.6 2020-01-06       A   3.0 Cv  2
# 2.7 2020-01-07       A   0.2 Cv  2
# 3   2020-01-10       A   4.0 Cv  3

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-