How to Change Values in a Vector in R

Changing values in a vector in R is actually pretty simple. To illustrate, let’s assume that you created two vectors containing the number of baskets that Granny and Geraldine made in six basketball games, as follows:

> baskets.of.Granny <- c(12,4,4,6,9,3)
> baskets.of.Geraldine <- c(5,3,2,2,12,9)

But suppose that Granny tells you that you made a mistake: In the third game, she made five baskets, not four. You can easily correct this mistake by using indices, as follows:

> baskets.of.Granny[3] <- 5
> baskets.of.Granny
[1] 12 4 5 6 9 3

The assignment to a specific index is actually a function as well. It’s different, however, from the brackets function because you also give the replacement values as an argument. Boring technical stuff, you say? Not if you realize that because the index assignment is a vectorized function, you can use recycling!

Imagine that you made two mistakes in the number of baskets that Granny’s friend Geraldine scored: She actually scored four times in the second and fourth games. To correct the baskets for Geraldine, you can use the following code:

> baskets.of.Geraldine[c(2,4)] <- 4
> baskets.of.Geraldine
[1] 5 4 2 4 12 9

How cool is that? You have to be careful, though. R doesn’t tell you when it’s recycling values, so a typo may give you unexpected results.

R doesn’t have an Undo button, so when you change a vector, there’s no going back. You can prevent disasters by first making a copy of your object and then changing the values in the copy, as shown in the following example. First, make a copy by assigning the vector baskets.of.Granny to the object Granny.copy:

> Granny.copy <- baskets.of.Granny

You can check what’s in both objects by typing the name on the command line and pressing Enter. Now you can change the vector baskets.of.Granny:

> baskets.of.Granny[4] <- 11
> baskets.of.Granny
[1] 12 4 5 11 9 3

If you make a mistake, simply assign the vector Granny.copy back to the object baskets.of.Granny, like this:

> baskets.of.Granny <- Granny.copy
> baskets.of.Granny
[1] 12 4 5 6 9 3
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.