[R] question regarding conversion from factor to vector

David Winsemius dwinsemius at comcast.net
Sat Mar 27 15:33:04 CET 2010


On Mar 26, 2010, at 12:37 PM, Oliver Kullmann wrote:

> Hello,
>
> let me show you the following part of a session:
>
>> table(E$singles)
>     0      1      2      3      4      5      6      7      8      
> 14     15
> 461752   5487     93    224    379    658   1099   4053      2    
> 1868      1
>    21     28     29     35     42     49     50     56     63      
> 70     77
>   904    560      1    348    275    126      1    156    103      
> 71     63
>    84     91     98    105    112    119    126    133    134     
> 140    147
>    51     35     37     16     19     17     14     27      1      
> 20     17
>   154    161    168    169    175    182    189    196    203     
> 210    217
>    16      8      7      1      7     12      5      6      3       
> 8      4
>   224    231    245    252    259    266    273    280    287     
> 294    301
>     6      5      5      1      2      3      4      2      2       
> 1      2
>   315    329    336    343    364    385    386    399    441     
> 476    560
>     2      2      1      2      3      2      1      1      1       
> 1      1
>> as.numeric(as.vector(as.data.frame(table(E$singles))$Var1)) %% 7
> [1] 0 1 2 3 4 5 6 0 1 0 1 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0  
> 0 0 0 0 1 0
> [39] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
>
> As you can see, the values of column "singles" of dataframe E show
> a strong regularity w.r.t. multiples of 7, and with the second line
> I checked that.
>
> Now I hope that there is a better way to get the vector of values out
> of the table-result? First I convert it into a dataframe, to get a
> name for the two vectors constituting the table, then a get a vector
> of strings(!), which are then converted to integers.

In this case where the is only one dimension, the table object is more  
like a named vector. The first "vector" in your terminology (but would  
be more accurately called "labels") can be accessed with:

  names( table(E$singles) )

If you want the counts without the lables , then just use the unname  
function:

unname( table(E$singles) )
-- 
David.
>
> By the way, the type of E$singles is integers.
>
> Thanks for your help!
>
> Oliver
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list