首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R:带组准则的行的迭代删除

R:带组准则的行的迭代删除
EN

Stack Overflow用户
提问于 2015-12-07 19:28:13
回答 2查看 53关注 0票数 2

如果行符合两个条件,我将尝试迭代删除它们:

  • 斜坡柱<0
  • 环群中Lfd的最大值

代码语言:javascript
复制
Ring <- c(1, 1, 1, 1, 2, 2, 2, 2)     
Lfd <- c(1:4, 1:4)     
slope <- c(2, 2, -1, -2, 2, -1, 2, -2)     
test <- data.frame(Ring, Lfd, slope)

  Ring Lfd slope  
1    1   1     2  
2    1   2     2  
3    1   3    -1  
4    1   4    -2  
5    2   1     2  
6    2   2    -1  
7    2   3     2  
8    2   4    -2       

在第一次迭代之后,它们应该看起来像

代码语言:javascript
复制
  Ring Lfd slope  
1    1   1     2  
2    1   2     2  
3    1   3    -1  
5    2   1     2  
6    2   2    -1  
7    2   3     2  

在第二次之后

代码语言:javascript
复制
  Ring Lfd slope  
1    1   1     2  
2    1   2     2  
5    2   1     2  
6    2   2    -1  
7    2   3     2 

我已经尝试过没有迭代:

代码语言:javascript
复制
test_out <- test %>%
  group_by(Ring) %>%
  filter(Lfd != which.max(Lfd) & (slope > 0)) %>%
  ungroup

在迭代中:

代码语言:javascript
复制
del.high.neg <- function(x) {
  success <- FALSE
  while (!success) {
    test_out <- test %>%
      group_by(Ring) %>%
      filter(Lfd == which.max(Lfd)) %>%
      select(Ring, Lfd, slope) %>%
      ungroup
    Index <- test_out[test_out$slope < 0, ]
    test_out <- test_out[!(test_out$Ring %in% Index),]
    success <- Index == NULL
  }
  return(x)
}
EN

回答 2

Stack Overflow用户

发布于 2015-12-07 20:05:36

我认为您是说要删除所有具有负slope和大于或等于Lfd最大值和非负slope的行的行。如果要在Ring中执行此操作,可以使用以下方法:

代码语言:javascript
复制
library(plyr)
testmax <- ddply(test,.(Ring),summarize,maxLfd = max(Lfd[slope>=0]))

test1 <- merge(test,testmax)
test_out <- test1[!(test1$Lfd>=test1$maxLfd & test1$slope<0),-4]

test_out
#   Ring Lfd slope
# 1    1   1     2
# 2    1   2     2
# 5    2   1     2
# 6    2   2    -1
# 7    2   3     2
票数 0
EN

Stack Overflow用户

发布于 2015-12-07 20:06:06

我认为这正是您想要的--它将删除数据末尾的每一行负数,直到达到第一个正值为止:

代码语言:javascript
复制
library(dplyr)
test %>% group_by(Ring) %>%
         mutate(row = row_number()) %>%
         filter(row <= max(which(slope > 0)))

Source: local data frame [5 x 4]
Groups: Ring [2]

   Ring   Lfd slope   row
  (dbl) (int) (dbl) (int)
1     1     1     2     1
2     1     2     2     2
3     2     1     2     1
4     2     2    -1     2
5     2     3     2     3

如果希望行列也删除,可以在select(-row)上添加。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34141580

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档