Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.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_Dataframe - Fatal编程技术网

R 在条件下删除值为零的行

R 在条件下删除值为零的行,r,dataframe,R,Dataframe,我有一个数据框: dt <- read.table(text = " 350 16 366 11 376 0 380 0 397 0 398 45 400 19 402 0 510 0 525 0 537 0 549 0 569 112 578 99") dt使用base R比较向上和向下位移向量的简单解决方案 dt[ !(c(dt$V2[-1],0) == 0 & c(0,dt$V2[-length(dt$V2)]) == 0 & dt$V2 == 0

我有一个数据框:

dt <- read.table(text = "
350 16 
366 11 
376  0
380  0
397  0
398 45  
400 19  
402 0
510 0
525 0
537 0
549 0
569 112
578 99")

dt使用
base R
比较向上和向下位移向量的简单解决方案

dt[ !(c(dt$V2[-1],0) == 0 & c(0,dt$V2[-length(dt$V2)]) == 0 & dt$V2 == 0), ]

使用
dplyr

dt %>%
  filter(lag(V2, 1) != 0 | lead(V2, 1) != 0 | V2 != 0)

    V1  V2
1  350  16
2  366  11
3  376   0
4  397   0
5  398  45
6  400  19
7  402   0
8  549   0
9  569 112
10 578  99

与其他回答相比,这并不是什么新鲜事,但我发现这个问题很有趣,因此我提出了自己的解决方案——瞧:

## Function to test if both neighbors of a vector element have the value 0
## Returns a logical vector.
neighbors_zero <- function(x) {
  ## left neighbor is zero?
  rn0 <- c(x[2:length(x)], x[1]) == 0
  ## right neighbor is zero?
  ln0 <- c(x[length(x)], x[1:(length(x)-1)]) == 0
  return(rn0 & ln0)
}

## Test if a value is itsself zero and between other zeros
zero_between_zeros <- dt$V2 == 0 & neighbors_zero(dt$V2)

dt[!zero_between_zeros, ]
###函数,用于测试向量元素的两个相邻元素的值是否均为0
##返回一个逻辑向量。
零的邻居
dt[ !(c(dt$V2[-1],0) == 0 & c(0,dt$V2[-length(dt$V2)]) == 0 & dt$V2 == 0), ]
dt %>%
  filter(lag(V2, 1) != 0 | lead(V2, 1) != 0 | V2 != 0)

    V1  V2
1  350  16
2  366  11
3  376   0
4  397   0
5  398  45
6  400  19
7  402   0
8  549   0
9  569 112
10 578  99
## Function to test if both neighbors of a vector element have the value 0
## Returns a logical vector.
neighbors_zero <- function(x) {
  ## left neighbor is zero?
  rn0 <- c(x[2:length(x)], x[1]) == 0
  ## right neighbor is zero?
  ln0 <- c(x[length(x)], x[1:(length(x)-1)]) == 0
  return(rn0 & ln0)
}

## Test if a value is itsself zero and between other zeros
zero_between_zeros <- dt$V2 == 0 & neighbors_zero(dt$V2)

dt[!zero_between_zeros, ]