2

不等式を満たす実際の値のエントリを含む列を含む、がありdata.tableます。これらのエントリをたとえば10の間隔で「グループ化」したいと思います。具体的には、値0.1を割り当てたいすべての値に、値0.2などを割り当てたいすべての値にDTC0 < x <= 1xC0 < x <=0.1xC0.1 < x <=0.2

以下は私が書いた関数で、これを実行できると思いました(簡単ですが、私はRに比較的慣れていません!)。

r = function(x,N){

  v = numeric(10)
  for(i in 1:N)
    v[i] = i/N*(x>(i-1)/N & x<=i/N)
   v = v[v!=0]
  return(v)

}

ここNで、は必要な間隔の数です。ただし、コード:

DT = DT[,newC:=r(x=C,N=10)]

次のエラーが発生します。

Warning messages:
1: In v[i] = i/10 * (x > (i - 1)/10 & x <= i/10) :
  number of items to replace is not a multiple of replacement length
2: In v[i] = i/10 * (x > (i - 1)/10 & x <= i/10) :
  number of items to replace is not a multiple of replacement length
...
10: In v[i] = i/10 * (x > (i - 1)/10 & x <= i/10) :
  number of items to replace is not a multiple of replacement length

どんな助けでも大歓迎です!乾杯

4

2 に答える 2

4

(より高速な)代替手段は、を使用することfindIntervalです。これは、と非常によく似た仕事をしcutますが、to-factorおよびfrom-factor変換を回避します。

  z1 <- findInterval(x,y)
  z1 <- tail(y,-1)[z1]

そして少しのベンチマーク

cutting <- function(){
  z <- cut(x,y,labels=tail(y,-1))
  #this generates a factor: 
  #you can convert it back to numeric
   z <- as.numeric(levels(z))[z]
  }

finding <- function(){
 z1 <- findInterval(x,y)
 z1 <- tail(y,-1)[z1]
}

microbenchmark(cutting(),finding())


##     Unit: microseconds
##       expr    min       lq   median      uq     max
## 1 cutting() 188.50 192.1175 193.6275 195.821 354.701
## 2 finding()  34.18  35.5140  37.5620  38.763  46.397
于 2013-02-13T22:42:42.397 に答える
2

関数でforループの行を試す場合は、次のように言いi = 1ますx = C

DT[,1/10 * (C > (1-1)/10 & C <= 1/10)]

同じ長さのベクトルが得られることに気付くでしょうC。エラーは、長さが1より大きいベクトルをに割り当てることができないことを示していますv[i]debug関数をステップスルーして(、、などの関数を使用してtracebackbrowser、適切な入力として必要なものが得られることを確認することをお勧めします。

関数を機能させる方法は次のとおりです。

r = function(x,N){

  for(i in 1:N)
    x[x>(i-1)/N & x<=i/N] <- i/N
  return(x)

}

Rには、これを行うための組み込みの方法もあります。

#sample data
set.seed(1)
x <- runif(100)
#to organize your data
y <- seq(0,1,.1)
z <- cut(x,y,labels=tail(y,-1))
#this generates a factor: 
#you can convert it back to numeric
z <- as.numeric(levels(z))[z]
于 2013-02-13T13:28:47.383 に答える