[R] Adding a column into the file

John jwd at surewest.net
Sun Jun 3 08:01:05 CEST 2012


On Fri, 1 Jun 2012 09:27:58 -0700 (PDT)
pigpigmeow <glorykwok at hotmail.com> wrote:

> Dear all,
> I have a lot of problems on R-programming.
> for example
> my csv. file is ..
> Date                  wrfRH wrfsolar wrfwindspeed wrfrain wrftd wrfta
> 21/10/2010 92.97 22.11 53.27 0 1546.337861 61.00852664
> 22/10/2010 87.35 21.99 40.89 0 1300.408288 62.85352227
> 23/10/2010 88.38 21.71 28.04 0.01 1381.768284 54.80594493
> 24/10/2010 92.32 15.45 22.38 0.51 1113.90981 39.46573663
> 25/10/2010 93.42 21.59 35.5 0.52 868.4895334 28.42952321
> 26/10/2010 93.38 20.15 42.58 0.07 1404.722837 40.29300856 
> i calculate the ratio of wrfRH/wrfsolar for each day.
> 
> that is  
> Date          wrfRH 
 wrfwindspeed wrfrain wrftd wrfta ratio 
> 21/10/2010 92.97 22.11 53.27 0 1546.337861 61.00852664  XXXX
> 22/10/2010 87.35 21.99 40.89 0 1300.408288 62.85352227  YYYY
> 23/10/2010 88.38 21.71 28.04 0.01 1381.768284 54.80594493 ZZZZ
> 24/10/2010 92.32 15.45 22.38 0.51 1113.90981 39.46573663 AAAA
> 25/10/2010 93.42 21.59 35.5 0.52 868.4895334 28.42952321 BBBB
> 26/10/2010 93.38 20.15 42.58 0.07 1404.722837 40.29300856  CCCC
> 
> how to add new column in the original file ? Anyone can help me?!
> 
First, that is not a csv file.  Your delimiter is a space.  Second, it
appears that the first and second records contain two spaces
between the wrtfa column and the ratio column.  Since you don't provide
an example how how you actually read the data table into R, there's no
way to say what else might be wrong.  If you specify an escaped space
as the delimiter, the read should fail at about the third line.  

Now, if you use R to calculate the ratio the story is different.  I
would guess you simply want to join the calulated field to your data
frame:

To move the new data to a data frame, calculate the new variable and
then assemble the new data frame:

ratio <- dat$wrfRH/dat$wrfsolar

then

newdataframe <- data.frame(dat, ratio)

which should yield what I believe you want.

That of course assumes that what you really want to do is simply add
the new column of calculated values to the original data.  There also
any number of very helpful books about R that can probably help.



More information about the R-help mailing list