【问题标题】:R Clever way to clean data frameR 清理数据框的聪明方法
【发布时间】:2016-07-30 02:07:42
【问题描述】:

我有一个包含两列的数据框,一个索引列,它索引第二个数据框中的行。这些行都包含一个特定的事件。这是哪个事件,编码在第二列,这里命名为code_start_stop

例子:

index <- c(769, 766, 810, 813, 830, 842, 842, 892, 907, 944)
code_start_stop <- c(2006, 2001, 2004, 1001, 1004, 2001, 1001, 1006, 2004, 1004)
replace_all <- data.frame(index, code_start_stop)

现在有成对的开始/停止代码,即 2001 和 1001、2002 和 1002 等。目的是,如果存在由开始标记包围的行(即此处为 2006)和相应的下一个停止标记(此处为 1006),这些行应从数据框中删除。 请注意,总是有成对的开始和停止标记。

任何关于如何做到这一点的聪明方法的建议都值得赞赏。谢谢!

【问题讨论】:

  • indexcode_start_stop这里的长度不同,所以replace_all不能用当前代码创建。

标签: r


【解决方案1】:

您的问题有点混乱,如果我错了,请纠正我。 以下应该有效:

startm <- 2006 #startmarker
endm   <- 1006 #endmarker

 #look for  row that contains markers
 index1 <- which(replace_all[,2]  == startm) 
 index2 <- which(replace_all[,2]  == endm)

 #subset accordingly
 replace_all <- replace_all[-(index1:index2),]

注意:这也会删除包含标记的行。如果您只想删除标记之间的行,请在子集步骤中添加 +1/-1。

【讨论】:

  • 非常感谢!但是,我首先有一对开始和结束标记:startm1 &lt;- 2001 endm1 &lt;- 1001 .... startm6 &lt;- 2006 endm6 &lt;- 1006 而且,每对标记可以在数据框中出现 n 次(这比上面的示例要大得多)。
  • 你可以简单地遍历这些对
【解决方案2】:

该解决方案现在基于马丁的建议,似乎效果很好。

我通过所有开始和结束标记对执行以下操作:

to_delete <- c()
## Care = 2001/1001
startm1 <- 2001
endm1 <- 1001
index1 <- which((replace_all[,2]  == startm1))
index2 <- which((replace_all[,2]  == endm1))
if(length(index1) !=0){
  for (i in 1:length(index1)){
    if (index2[i]-index1[i]>1){
      to_delete <- c(to_delete, (((index1[i])+1):((index2[i])-1)))
    }
  }
}

...遍历所有其他开始/停止标记对,然后删除to_delete

if (length(to_delete) != 0){
    replace_all <- replace_all[-to_delete,]
  }
    replace_all <- replace_all[,1]
  }

【讨论】:

    猜你喜欢
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多