Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

r - Filter logical columns

Not able to filter on logical columns below. Wanted to check if there is way to filter. If I filter based on false, NA row becomes all NA. I need rows with NA but with values in other column?

asd <- data.frame(Cat = c("A","B","B","A","B","A"), Start_num = c(2, 5, 1, 6, 6, 4), End_num = c(3, 7, 4, 7, 8, 5))

new <- asd %>% arrange(Cat,Start_num) %>%
    group_by(Cat) %>%
    mutate(Var=lead(Start_num)>End_num)

new <- as.data.frame(new)
new[new$Var != FALSE,]
      Cat Start_num End_num  Var
1       A         2       3 TRUE
2       A         4       5 TRUE
NA   <NA>        NA      NA   NA
4       B         1       4 TRUE
NA.1 <NA>        NA      NA   NA

```
question from:https://stackoverflow.com/questions/65936682/filter-logical-columns

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to subset on the TRUE values but also have NA values, you need to subset both on NA and TRUE:

new[!is.na(new$Var) & new$Var == TRUE,]
# A tibble: 3 x 4
# Groups:   Cat [2]
  Cat   Start_num End_num Var  
  <chr>     <dbl>   <dbl> <lgl>
1 A             2       3 TRUE 
2 A             4       5 TRUE 
3 B             1       4 TRUE 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...