2012-08-08 74 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

相关问题