[R] Matrix to data.frame with factors

Bert Gunter gunter.berton at gene.com
Fri Oct 19 16:21:26 CEST 2012


Well, strictly speaking, this is still doing it "one variable at a
time." The interpreted loop is hidden, but it's still happening.

A loop free but clumsier approach is:

y <- data.frame(matrix(as.character(x),nrow = nrow(x)))

## Note also that the original column names will be lost and will have
to be added to the data frame.

It would also not surprise me if for such a small matrix that Rui's
version were faster.

-- Bert

On Fri, Oct 19, 2012 at 7:07 AM, Rui Barradas <ruipbarradas at sapo.pt> wrote:
> Hello,
>
> Try the following.
>
> x <- matrix(sample(0:1, 12, TRUE), ncol = 4)
> y <- data.frame(apply(x, 2, factor))
> str(y)
>
> Hope this helps,
>
> Rui Barradas
> Em 19-10-2012 12:04, brunosm escreveu:
>>
>> Hi all,
>>
>> I have a matrix with 100 variables: each variable as a value of 0 or 1.
>>
>> What i want to do is convert this matrix to a data.frame but convert all
>> the
>> variables to factors (0 and 1) also.
>>
>> I know i can do this one variable a time but i have 100 variables...
>>
>> Any easy way of doing this??
>>
>> Thanks a lot,
>>
>> Bruno
>>
>>
>>
>> --
>> View this message in context:
>> http://r.789695.n4.nabble.com/Matrix-to-data-frame-with-factors-tp4646730.html
>> Sent from the R help mailing list archive at Nabble.com.
>>
>> ______________________________________________
>> 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.
>
>
> ______________________________________________
> 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.



-- 

Bert Gunter
Genentech Nonclinical Biostatistics

Internal Contact Info:
Phone: 467-7374
Website:
http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm




More information about the R-help mailing list