0
  rate   len ADT trks      sigs1 slim shld lane acpt  itg lwid hwy
1  4.58  4.99  69    8 0.20040080   55   10    8  4.6 1.20   12 FAI
2  2.86 16.11  73    8 0.06207325   60   10    4  4.4 1.43   12 FAI
3  3.02  9.75  49   10 0.10256410   60   10    4  4.7 1.54   12 FAI
4  2.29 10.65  61   13 0.09389671   65   10    6  3.8 0.94   12 FAI
5  1.61 20.01  28   12 0.04997501   70   10    4  2.2 0.65   12 FAI
6  6.87  5.97  30    6 2.00750419   55   10    4 24.8 0.34   12  PA
7  3.85  8.57  46    8 0.81668611   55    8    4 11.0 0.47   12  PA
8  6.12  5.24  25    9 0.57083969   55   10    4 18.5 0.38   12  PA
9  3.29 15.79  43   12 1.45333122   50    4    4  7.5 0.95   12  PA

I got a question in adding a new column, my data frame is called highway1,and i want to add a column named S/N, as slim divided by acpt, what can I do?

Thanks

A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485

2 Answers2

1
> mydf$SN <- mydf$slim/mydf$acpt
> mydf
  rate   len ADT trks      sigs1 slim shld lane acpt  itg lwid hwy        SN
1 4.58  4.99  69    8 0.20040080   55   10    8  4.6 1.20   12 FAI 11.956522
2 2.86 16.11  73    8 0.06207325   60   10    4  4.4 1.43   12 FAI 13.636364
3 3.02  9.75  49   10 0.10256410   60   10    4  4.7 1.54   12 FAI 12.765957
4 2.29 10.65  61   13 0.09389671   65   10    6  3.8 0.94   12 FAI 17.105263
5 1.61 20.01  28   12 0.04997501   70   10    4  2.2 0.65   12 FAI 31.818182
6 6.87  5.97  30    6 2.00750419   55   10    4 24.8 0.34   12  PA  2.217742
7 3.85  8.57  46    8 0.81668611   55    8    4 11.0 0.47   12  PA  5.000000
8 6.12  5.24  25    9 0.57083969   55   10    4 18.5 0.38   12  PA  2.972973
9 3.29 15.79  43   12 1.45333122   50    4    4  7.5 0.95   12  PA  6.666667

I hope an explanation is not necessary for the above.

A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
  • Thanks Ananda, I tried this before, but it always shows an error, because the name is"S/N", i just type > mydf$S/N <- mydf$slim/mydf$acpt, but it's an error. – user3472222 Mar 28 '14 at 11:11
  • @user3472222, that's because "/" is not a valid character to be used in a variable name. If you really want to do that, you could use `mydf$"S/N" <- mydf$slim/mydf$acpt`, but that might just make things more complicated later on since you'll always need to quote the variable names when you need to refer to them. – A5C1D2H2I1M1N2O1R2T1 Mar 28 '14 at 11:29
0

While $ is the preferred route, you can also consider cbind.

First, create the numeric vector and assign it to SN:

SN <- Data[,6]/Data[,9]

Now you use cbind to append the numeric vector as a column to the existing data frame:

Data <- cbind(Data, SN)

Again, using the dollar operator $ is preferred, but it doesn't hurt seeing what an alternative looks like.

Eric
  • 2,699
  • 5
  • 17