【问题标题】:R: Iterative deletion of rows with group criteriaR:迭代删除具有组标准的行
【发布时间】:2016-03-12 12:41:06
【问题描述】:

我正在尝试迭代删除行,如果它们满足两个条件:

  • 斜柱
  • 环组内 Lfd 的最大值

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       

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

  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  

第二次喜欢后

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

我已经尝试过没有迭代:

test_out <- test %>%
  group_by(Ring) %>%
  filter(Lfd != which.max(Lfd) & (slope > 0)) %>%
  ungroup

还有迭代:

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)
}

【问题讨论】:

  • 您的第一个 ungroup() 缺少括号。你的函数接受一个你从不使用的参数 x 。论据应该是测试。此外,您的函数将创建一个无限循环,因为您实际上并没有修改测试

标签: r filter iteration


【解决方案1】:

我认为您是说要删除所有具有负数 slope 并且具有大于或等于最大值为 Lfd 且非负数的行的 Lfd 的行slope。如果您想在Ring 内执行此操作,可以使用以下命令:

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

【讨论】:

  • max(test$Lfd[test$slope&gt;=0]) 从整个数据帧中调用 Lfd 的整体最大值,但不在环组内
  • 没错。这个问题没有提到关于环组的任何事情。如果你想在响铃组中更新,我可以稍后更新。
【解决方案2】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2019-01-15
    • 2019-11-01
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多