mCorey
mCorey

Reputation: 295

Add value to some cases in data frame in R

I have a data frame with a numeric column called store that has some negative values. I'd like to add 1440 to the negative , but am having trouble. My data looks like this:

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

I can replace the values using temp[temp$score< 0] <-8888.

But, I when I try to add value to the variable using: temp[temp$score < 0] <- temp$score + 1440, I get an warning that says:

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

And then I get some odd values returned:

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

Am I calling the function wrong or am I selecting the cases wrong?

Upvotes: 0

Views: 779

Answers (2)

Spacedman
Spacedman

Reputation: 94182

As mentioned in comments, if there's NA data, then subscripting will fail:

> 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

So use 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

Upvotes: 2

Edward
Edward

Reputation: 5537

From your warning message, it seems like you were trying to do the following:

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

The problem here is that you are replacing a vector with one that is a different length, as the warning message suggests. You shortened the left-hand side of the assignment, but not the right-hand side - the solution would be to shorten the right-hand side too, as follows:

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

Upvotes: 5

Related Questions