[R] converting character matrix to a dataframe

From: John M. Miyamoto <jmiyamot_at_u.washington.edu>
Date: Fri 24 Feb 2006 - 12:16:37 EST


Dear R-Help,

    Suppose I have a character matrix, e.g.,

(ch.mat <- matrix(c('a','s','*','f','w','*','k','*','*','f','i','o'),
ncol=3))

When I convert 'ch.mat' to a dataframe, the columns are converted to factors:

(d1 <- data.frame(ch.mat))

mode(d1[,1])
is.factor(d1[,1])

To prevent this, I can use 'I' to protect the column vectors:

(d2 <- data.frame(x1 = I(ch.mat[,1]), x2 = I(ch.mat[,2]), x3 =
I(ch.mat[,3])))
mode(d2[,1])
is.factor(d2[,2])

but this method is cumbersome if the matrix has many columns. The following code is reasonably efficient even if the matrix has arbitrarily many columns.

(d3 <- data.frame(apply(ch.mat,2,function(x) data.frame(I(x)))))
mode(d3[,1])
is.factor(d3[,1])

Question: Is there a more efficient method than the last one for converting a character matrix to a dataframe while preventing the automatic conversion of the column vectors to factors?

John



John Miyamoto, Dept. of Psychology, Box 351525 University of Washington, Seattle, WA 98195-1525 Phone 206-543-0805, Fax 206-685-3157
Homepage http://faculty.washington.edu/jmiyamot/

R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Fri Feb 24 12:24:34 2006

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:42:44 EST