[R] Data frames

Eric Lecoutre lecoutre at stat.ucl.ac.be
Mon Apr 25 11:50:07 CEST 2005


> I have two questions about data frames:
> 
> (1) How can one extract a simple matrix
> from a data frame? I tried
> 
>       Matrixfromdf = function (frame,without=1)
>       {a=frame[colnames(frame)[-without]]
>       v=unlist(a,use.names=F)
>       matrix(v,ncol=ncol(a))}
> 
> but it works well only for without=1,
> perhaps also because the function in (2)
> gives probably a different meaning to
> the first column.


?as.matrix
data(iris)
as.matrix(iris[,-5]) # numeric
as.matrix(iris[,-1]) # character


> (2) How does one define a void data frame
> with only column names but no values?
> I tried this indirect way:
> 
>      # Void df with titles from ...
>      Newvoid = function (...)
>      {a=c(...); m=length(a)
>      titles=paste(a,collapse=' ')
>      conn=textConnection(titles)
>      tab=read.table(conn,header=T)
>      close(conn); tab}

Basically, you have to create the sctruture by providing one observation
This will allow you to specify the classes of the variables.

> data.frame(list(x=1,y="character"))[-1,]
[1] x y
<0 rows> (or 0-length row.names)


Eric




More information about the R-help mailing list