2012-08-08 58 views
0

我有數值列稱爲商店具有一些負值的數據幀。我想添加1440到負面,但有麻煩。我的數據如下所示:到一些情況下在數據幀添加值中的R

score 
    1 816 
    2 -200 
    3 976 
    4 -376 
    5 1 
    6 121 
    7 -331 

我可以使用temp[temp$score< 0] <-8888替換這些值。

但是,我當我嘗試值添加到使用變量:temp[temp$score < 0] <- temp$score + 1440,我得到的是說,一個警告:

Warning message: In temp$score[temp$score < 0] <- temp$score + 1440 
:number of items to replace is not a multiple of replacement length 

然後,我得到一些奇怪的值返回:

score 
1 816 
2 2256 
3 976 
4 1240 
5  1 
6 121 
7 2416 

我是否調用了錯誤的函數,或者我是否選擇了錯誤的情況?

回答

5

從你的警告信息,好像你試圖做到以下幾點:

temp$score[temp$score < 0] <- temp$score + 1440 

這裏的問題是,要更換一個這是一個不同長度的矢量,作爲警告信息提示。您縮短了分配的左側,而不是右側 - 的解決辦法是縮短右手方太,具體如下:

score <- c(816,-200,976,-376,1,121,-331) 
temp <- data.frame(score) 
temp$score[temp$score < 0] <- temp$score[temp$score < 0] + 1440 
+0

省長,謝謝! – mCorey 2012-08-08 00:54:10

+1

沒問題!我無法運行temp [temp $ score <0 < - temp $ score + 1440' ... ...在這種情況下,我不得不假設您要從警告消息中執行的操作。作爲一個領導者,如果他們可以複製代碼並運行它,那麼人們會更容易回答問題 - 因此,當您提出問題時,檢查是否可以自己做這件事是個好主意。 – Edward 2012-08-08 00:55:55

+3

只是爲了好玩,你也可以這樣做:'temp $ score < - temp $ score + 1440 *(temp $ score <0)'。我懷疑對於非常大的向量,這可能會比較慢,但使用從邏輯到1和0的隱式轉換通常很方便。 – 2012-08-08 01:00:28

2

正如評論所說,如果有NA數據,那麼下標會失敗:

> temp 
    score z 
1 123 1 
2  NA 2 
3 345 3 
4 -10783 4 
5 1095 5 
6 873 6 
> temp$score[temp$score < 0] <- temp$score[temp$score < 0] + 1440 
Error in temp$score[temp$score < 0] <- temp$score[temp$score < 0] + 1440 : 
    NAs are not allowed in subscripted assignments 

所以使用which

> temp$score[which(temp$score < 0)] <- temp$score[which(temp$score < 0)] + 1440 
> temp 
    score z 
1 123 1 
2 NA 2 
3 345 3 
4 -9343 4 
5 1095 5 
6 873 6 
+0

嘿,沒有公平地引用你自己的意見! :-) – 2012-08-08 12:54:35

相關問題