[R] data.frame query

J.delasHeras at ed.ac.uk J.delasHeras at ed.ac.uk
Thu Oct 21 19:31:15 CEST 2010


you forgot to include "output1" in your cbind call.

what I normally do is initialise the variable where I want to store  
the dataframe prior to starting the loop:

output1<-NULL

then run the loop, and within it there should be a:

output1<-cbind(output1, newdata)

where 'newdata' will be the new column the loop just calculated and I  
want to add to the dataframe.

That way the dataframe grows as the data is produced.

As long as you don't have many columns/rows to add it will work fine.  
When I was handling large dataframes I found it was a very inefficient  
method and it takes too long after it has a few thousand data points.  
In that case it's much better to calculate beforehand how big the  
dataframe will be, and initialise it in full size, then just fill in  
as needed.

I hope this helps.

Jose





Quoting Etn <2nuzzbot at gmail.com>:

> Hi All,
>
> Apologies for the simplicity of my question, but I would be grateful for any
> advice. Thanks
>
> I'm trying to put the output from a for loop into a data frame, however I
> have not been successful.
>
> The steps I have taken are:
>
>
>
> *R-code:*
>
>> for (k in 1:(nt-1-n0) ){
>>    n<- n0-1+k
>>    lam=n/nt
>>    Q=x[n]
>
>> output1<-data.frame(cbind(k,n,lam,Q))
>> output1
>>  }
>
>> output1
>
>
> *R-Output *
>      k    n  lam   Q
> 1 14  18  0.9   18
>
>
> I would like the output in this format, but for all the values of k (i.e.
> 1-14 as opposed to just the last value)
>
>
> I have also tried
>
> *R-code:*
>
>> nt=20
>> n0=5
>> x=c(1:20)
>> for (k in 1:(nt-1-n0) ){
>>      n<- n0-1+k
>>      lam=n/nt
>>      Q=x[n]
>
>> output1<-data.frame(cbind(k,n,lam,Q))
>> print(output1)
>>  }
>
>
> *R-Output  *
>
>     k n  lam Q
> 1 1 5 0.25 5
>    k n lam Q
> 1 2 6 0.3 6
>    k n  lam Q
> 1 3 7 0.35 7
>    k n lam Q
> 1 4 8 0.4 8
>   k n  lam Q
> 1 5 9 0.45 9
>   k  n lam  Q
> 1 6 10 0.5 10
>   k  n  lam  Q
> 1 7 11 0.55 11
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>



-- 
Dr. Jose I. de las Heras                      Email: J.delasHeras at ed.ac.uk
The Wellcome Trust Centre for Cell Biology    Phone: +44 (0)131 6507095
Institute for Cell & Molecular Biology        Fax:   +44 (0)131 6507360
Swann Building, Mayfield Road
University of Edinburgh
Edinburgh EH9 3JR
UK


-- 
The University of Edinburgh is a charitable body, registered in
Scotland, with registration number SC005336.



More information about the R-help mailing list