2

データフレームがあり、カテゴリ内の数列に基づい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

1ずつ増加する行だけが必要で、2つ増加するx行は必要ありません。x

    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

要素間で少し引き算をして、違いがあるかどうかを確認>1し、これをaと組み合わせる必要があると思いましたddplyが、これは面倒なようです。sequence欠けている機能はありますか?

4

2 に答える 2

3

差分の使用

df[which(c(1,diff(df$x))==1),]
于 2012-11-30T12:38:06.610 に答える
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
于 2012-11-30T14:01:08.210 に答える