3

私のデータフレーム:

Dead4   Dead5
0       0
0       0
0       0
1       2
0       0
0       0
1       2
0       0
1       0
0       1
1       1
5      10

同じ行で Dead5 が Dead4 よりも大きいときはいつでも、コードで 2 つの値を減算し、その値を Dead5 に配置します。

indices<- (t$Dead5 > t$Dead4) 
t$Dead6[indices]<- (t$Dead6) - (t$Dead5)


Warning message:
In t$Dead6[indices] <- (t$Dead6) - (t$Dead5) :
  number of items to replace is not a multiple of replacement length

私が間違っていることを説明し、これを行う数行のコードを書くのを手伝ってくれる人はいますか?

4

4 に答える 4

4

あなたはこれを行うことができます:

indices <- (t$Dead5 > t$Dead4) # indices is a logical vector with TRUE and FALSE

t$Dead5[indices] <- (t$Dead5 - t$Dead4)[indices]

次のような、data.frame を使用した他の操作にも適用されます。

t$Dead6[indices] <- (t$Dead6 - t$Dead5)[indices]

Dead6が存在する場合。それぞれの側で、ある値のみindicesTRUE取得されるため、置換値と置換値は同じ長さであり、警告は表示されません。

あなたが間違っていたのは、完全な(t$Dead5 - t$Dead4)ベクトルを置換として与えていたことです。これは、の回数よりも長いindicesですTRUE(左側の置換された値)。

R は置換ベクトルの最初の値のみを使用し、警告を出していました。

于 2014-01-23T22:31:40.873 に答える