Home > Enterprise >  Remove the lines that have numbers = NA
Remove the lines that have numbers = NA

Time:10-05

I would like to remove the lines that have Numbers = NA from my datas variable. I'll insert the executable code below for you to see.

library(dplyr)
library(tidyverse)
library(lubridate)
library(data.table)

df1 <- structure(
  list(date= c("2021-06-28","2021-06-28","2021-06-28","2021-06-28","2021-06-28",
       "2021-06-28","2021-06-28","2021-06-28"),
       date2 = c("2021-06-30","2021-06-30","2021-06-30","2021-07-01","2021-07-01","2021-07-01","2021-07-01","2021-07-01"),
       Code = c("ABC","CDE","FGH","ABC","CDE","FGH","ABC","CDE"),
       DR01 = c(4,1,4,3,3,4,3,6), DR02= c(4,2,6,7,3,2,7,4),DR03= c(9,5,4,3,3,2,1,5),
       DR04 = c(5,4,3,3,6,2,1,9),DR05 = c(5,4,5,3,6,2,1,9),
       DR06 = c(2,4,3,3,5,6,7,8),DR07 = c(2,5,4,4,9,4,7,8),
       DR08 = c(0,0,0,1,2,0,0,0),DR09 = c(0,0,0,0,0,0,0,0),DR010 = c(0,0,0,0,0,0,0,0),DR011 = c(4,0,0,0,0,0,0,0), 
       DR012 = c(0,0,0,3,0,0,0,5),DR013 = c(0,0,1,0,0,0,2,0),DR014 = c(0,0,0,1,0,2,0,0)),
  class = "data.frame", row.names = c(NA, -8L))

df1<-df1 %>% mutate(index=row_number()) %>%
  pivot_longer(starts_with('DR')) %>%
  mutate(rleid=rleid(value==0)) %>%
  group_by(index) %>%
  mutate(value=replace(value, value==0 & rleid==last(rleid), NA)) %>%
  select(-index, -rleid) %>%
  pivot_wider(names_from = name, values_from = value)

dmda<-"2021-07-01"


datas <- df1%>%
  filter(date2 == ymd(dmda)) %>% 
  group_by(Code) %>%
  summarize(across(starts_with("DR0"), sum)) %>%
  pivot_longer(cols = -Code, names_pattern = "DR0(. )", 
               values_to = "val") %>% 
  mutate(name = readr::parse_number(name))
colnames(datas)[-1] <-c("Days","Numbers")

CodePudding user response:

We can use filter with complete.cases

library(dplyr)
datas <- datas %>% 
    filter(complete.cases(Numbers))

Or may also use na.omit

datas <- na.omit(datas)

Or in the code, specify values_drop_na = TRUE in pivot_longer

datas <- df1%>%
  filter(date2 == ymd(dmda)) %>% 
  group_by(Code) %>%
  summarize(across(starts_with("DR0"), sum)) %>%
  pivot_longer(cols = -Code, names_pattern = "DR0(. )", 
               values_to = "val", values_drop_na = TRUE) %>% 
  mutate(name = readr::parse_number(name))
colnames(datas)[-1] <-c("Days","Numbers")
  •  Tags:  
  • r
  • Related