[R] Populating then sorting a matrix and/or data.frame

Noah Silverman noah at smartmediacorp.com
Fri Nov 12 02:46:42 CET 2010


David,

Great solution.  While a bit longer to enter, it lets me explicitly
define a type for each column. 

Thanks!!!

-N

On 11/11/10 4:02 PM, David Winsemius wrote:
>
> On Nov 11, 2010, at 6:38 PM, Noah Silverman wrote:
>
>> That makes perfect sense.  All of my numbers are being coerced into
>> strings by the c() function.  Subsequently, my data.frame contains all
>> strings.
>>
>> I can't know the length of the data.frame ahead of time, so can't
>> predefine it like your example.
>> One thought would be to make it arbitrarily long filled with 0 and
>> delete off the unused rows.  But this seems rather wasteful.
>
> Although it might be faster, though. Here is a non-c() method using
> instead the list function (with options(stringsAsFactors=FALSE). List
> does not coerce to same mode and rbind.dta.frame will accept a list as
> a row argument:
>
> results <- data.frame(a=vector(mode="character", length=0) ,
>                       b=vector(mode="numeric", length=0),
>                      cc=vector(mode="numeric", length=0), # note: 
> avoid "c" as name
>                       d=vector(mode="numeric", length=0))
>  n = 10
>  for(i in 1:n){
>      a = LETTERS[i];
>      b = i;
>      cc = 3*i + 2
>      d = rnorm(1);
>      results <- rbind(results, list(a=a,b=b,cc=cc,d=c))
>               }
>  results
>    a  b cc  d
> 2  A  1  5  5
> 21 B  2  8  8
> 3  C  3 11 11
> 4  D  4 14 14
> 5  E  5 17 17
> 6  F  6 20 20
> 7  G  7 23 23
> 8  H  8 26 26
> 9  I  9 29 29
> 10 J 10 32 32
>
> OOOPs used d=c and there was a "c" vector hanging around to be picked up.
>



More information about the R-help mailing list