0

I have a dataset that looks like this:

   A  B  C   D
1. 5  4  4   4
2. 5  4  4   4
3. 5  4  4   4
4. 5  4  4   4
5. 5  4  4   4
6. 5  4  4   4
7. 5  4  4   4

I'd like to add a "zero" to all variables in column C. For example, like this:

   A  B  C   D
1. 5  4  40  4
2. 5  4  40  4
3. 5  4  40  4
4. 5  4  40  4
5. 5  4  40  4
6. 5  4  40  4
7. 5  4  40  4

How do I do this?

chembrad
  • 887
  • 3
  • 19
  • 33
R newbie
  • 3,127
  • 2
  • 13
  • 5
  • 5
    As your questions get more and more complicated, you might start thinking of producing a reproducible example. See how to make one here: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Roman Luštrik Sep 08 '12 at 06:48

3 Answers3

4

Just multiply column C by 10. Assuming your data.frame is called myData:

myData$C <- myData$C*10
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
4

I don't really like constantly having to refer to myData$A to refer to the A column. A nice alternative expression is to use within:

myData = within(myData, {
   C = C * 10
   D = D + 4
   E = C + D
 })

especially when more column manipulations need to be done in the same data.frame I like this syntax better. Or even better:

myData = transform(myData, C = C * 10, D = D + 4, E = C + D)

or use mutate from the plyr package. This has the advantage over transform that it works iteratively, allowing you to use newly created columns:

# fails
myData = transform(myData, C = C * 10, new_col = C + 4, even_newer = new * 3) 
#works  
myData = mutate(myData, C = C * 10, new_col = C + 4, even_newer = new * 3)
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
2

If your data is numeric, mrdwab's suggestion is the best:

myData$C <- myData$C*10

This style works for the "data.frame". So if you keep your data in a matrix you should use:

myData[,3] = myData[,3] * 10

Finally if your data is NOT NUMERIC (character), you can act as below:

myData$C = paste(myData$C, "0", sep="")

Ali
  • 9,440
  • 12
  • 62
  • 92