[R] convert matrix to data frame

Petr Pikal petr.pikal at precheza.cz
Fri Jan 6 08:06:15 CET 2006


Hi

On 5 Jan 2006 at 15:11, Chia, Yen Lin wrote:

Date sent:      	Thu, 5 Jan 2006 15:11:18 -0800
From:           	"Chia, Yen Lin" <yen.lin.chia at intel.com>
To:             	<r-help at stat.math.ethz.ch>
Subject:        	[R] convert matrix to data frame

> Hi all,
> 
> 
> 
> Suppose I have a 4 x 2 matrix  A and I want to select the values in
> second column such that the value in first column equals to k.
> 
> 
> 
> I gave the colnames as alpha beta, so I was trying to access the info
> using
> 
> 
> 
> A$beta[A[,1]==k], however, I was told it's not a data frame, I can get
> the object by using dollar sign.  I tried data.frame(A), but it didn't
> work.  

I believe its because matrix has a bit different structure from 
data.frame so its columns can not be simply called by names. But I 
wonder why data.frame(A) does not work for you? See below.

 > str(A)
 `data.frame':   4 obs. of  2 variables:
  $ alpha: num  -1.181 -0.415  2.087  1.422
  $ beta : num  -0.0889  0.6828 -0.7035 -0.3351 

 > str(mat)
   num [1:4, 1:2] -1.1813 -0.4152  2.0865  1.4216 -0.0889 ...
  - attr(*, "dimnames")=List of 2
   ..$ : chr [1:4] "1" "2" "3" "4"
   ..$ : chr [1:2] "alpha" "beta" 

 > B<-data.frame(mat) 

 > str(B)
 `data.frame':   4 obs. of  2 variables:
  $ alpha: num  -1.181 -0.415  2.087  1.422
  $ beta : num  -0.0889  0.6828 -0.7035 -0.3351

 > mat$alpha[mat[,1]<0]
 NULL
 > B$alpha[mat[,1]<0]
 [1] -1.181258 -0.415175




> 
> 
> 
> Any input on this will be very appreciated.  Thanks.
> 
> 
> 
> I tried looking in the manual, but I think I'm might be wrong about
> the keywords.
> 
> 
> 
> Yen Lin
> 
> 
>  [[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at 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

Petr Pikal
petr.pikal at precheza.cz




More information about the R-help mailing list