简体   繁体   English

按值过滤行,除非没有行满足条件

[英]Filter rows by value unless no row meet condition

In R I have the following dataset and I would want remove rows if Per<98, unless no rows with the same value in A meet this condition (then add 0):在 R 我有以下数据集,如果 Per<98,我想删除行,除非 A 中没有具有相同值的行满足此条件(然后添加 0):

df <- cbind(c("D1", "D1", "D1", "D1", "D2", "D2", "D2", "D2", "D3", "D3", "D3", "D3"), c(99.8, 99.5, 98.7, 98, 97.8, 97.3, 96, 95.9, 95, 94.9, 94.5, 94), c("sp", "sp", "sp", "sp", "sp", "sp", "sp", "sp", "sp", "sp", "sp", "sp")) colnames(df) <- cbind("A", "Per", "B")

The expected result would be预期的结果是

df <- cbind(c("D1", "D1", "D1", "D1", "D2", "D3"), c(99.8, 99.5, 98.7, 98, 0, 0), c("sp", "sp", "sp", "sp", "sp", "sp")) colnames(df) <- cbind("A", "Per", "B")

This should do the trick.这应该可以解决问题。

library(dplyr)
df2=as.data.frame(df, stringsAsFactors=FALSE) %>% mutate(Per=as.numeric(Per))
j=1
for (i in 1:nrow(df2)) {
  print(i)
  if ((sum(df2$A==df2[j,"A"])==1) & (df2[j,"Per"]<98)) {
    df2[j, "Per"]=0
  } else if (df2[j,"Per"] < 98) {
    df2=df2[-j,]
    next
  }
  j=j+1
}
df2

    A  Per  B
1  D1 99.8 sp
2  D1 99.5 sp
3  D1 98.7 sp
4  D1 98.0 sp
8  D2  0.0 sp
12 D3  0.0 sp

If it needs to be a matrix,如果它需要是一个矩阵,

df2=as.matrix(df2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM