[R] Creating a dataframe from several numeric and character vectors

John Fox jfox at mcmaster.ca
Tue Nov 6 22:28:12 CET 2001


Dear Svend,

At 06:57 PM 11/6/2001 +0100, Sven Garbade wrote:

>I want to combine some numeric vectors and one character vector to a
>dataframe and did this:
>
>     dat <- cbind(type, key,response, st)
>     dimnames(dat) <- list(NULL, labels)
>     dat <- data.frame(as.numeric(dat$"type"),
>as.numeric(dat$"key"),
>as.numeric(dat$"response"), dat$"st")
>
>where st is the character vector. I got this error:
>
>Error in "names<-.default"(*tmp*, value = vnames) :
>         names attribute must be the same length as the vector
>
>If I only type
>
>     dat <- data.frame(dat)
>
>then all variables are factors. I need all variables as numeric except
>st. How can I do it?

The problem here is that cbind coerces all of the data to character, since 
the matrix that it creates has to be homogenous. The solution is simply to 
use data.frame directly, as in:

         data <- data.frame(type, key, response, st)

Note that, by default, st will be converted into a factor in the data 
frame. If you want to preserve it as a character vector, protect it with 
the I function:

         data <- data.frame(type, key, response, I(st))

I hope that this helps,
  John


-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox
-----------------------------------------------------

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list