【问题标题】:subset data frame on vector sequence向量序列上的子集数据框
【发布时间】:2012-12-01 00:43:34
【问题描述】:

我有数据框 df,我想根据分类中的数字序列对 df 进行子集化。

 x  <- c(1,2,3,4,5,7,9,11,13)
 x2 <- x+77 
 df <- data.frame(x=c(x,x2),y= c(rep("A",9),rep("B",9)))

 df
    x y
1   1 A
2   2 A
3   3 A
4   4 A
5   5 A
6   7 A
7   9 A
8  11 A
9  13 A
10 78 B
11 79 B
12 80 B
13 81 B
14 82 B
15 84 B
16 86 B
17 88 B
18 90 B

我只想要 x 增加 1 的行,而不是 x 增加 2 的行:例如

    x y
1   1 A
2   2 A
3   3 A
4   4 A
5   5 A
10 78 B
11 79 B
12 80 B
13 81 B
14 82 B

我想我必须在元素之间做一些减法并检查差异是否为 &gt;1 并将其与 ddply 结合起来,但这似乎很麻烦。我是否缺少某种sequence 函数?

【问题讨论】:

  • 91 B 第 19 行的情况下你想返回什么?
  • @BenBarnes 谢谢你的想法很笼统,但在我的例子中,这不应该发生。
  • ?diff 将是一个很好的起点(例如diff(df$x)),但您需要进行一些调整才能使其正常工作。顺便说一句,xx2 的值不在您的问题中。
  • @mrdwab 谢谢更正,我会检查diff 刚才

标签: r


【解决方案1】:

使用差异

df[which(c(1,diff(df$x))==1),]

【讨论】:

  • 非常感谢,这并没有抓住78 B,但是当我拆分应用时就可以了。
【解决方案2】:

您的示例似乎表现良好,@agstudy 的回答可以很好地处理。不过,如果您的数据有朝一日会出现问题...

myfun <- function(d, whichDiff = 1) {
  # d is the data.frame you'd like to subset, containing the variable 'x'
  # whichDiff is the difference between values of x you're looking for

  theWh <- which(!as.logical(diff(d$x) - whichDiff))
  # Take the diff of x, subtract whichDiff to get the desired values equal to 0
  # Coerce this to a logical vector and take the inverse (!)
  # which() gets the indexes that are TRUE.

  # allWh <- sapply(theWh, "+", 1)
  # Since the desired rows may be disjoint, use sapply to get each index + 1
  # Seriously? sapply to add 1 to a numeric vector? Not even on a Friday.
  allWh <- theWh + 1

  return(d[sort(unique(c(theWh, allWh))), ])
}

> library(plyr)
> 
> ddply(df, .(y), myfun)
    x y
1   1 A
2   2 A
3   3 A
4   4 A
5   5 A
6  78 B
7  79 B
8  80 B
9  81 B
10 82 B

【讨论】:

    猜你喜欢
    • 2015-12-24
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 2022-01-22
    • 2017-01-22
    • 2013-02-20
    相关资源
    最近更新 更多