[R] How to create a numeric data.frame

Patrizio Frederic frederic.patrizio at gmail.com
Mon Jun 13 18:49:40 CEST 2011


>
> Which results in vector of numbers
>
> str(as.numeric(as.matrix(a)))
>  num [1:100] 0.82 -1.339 1.397 0.673 -0.461 ...
>
> data frame is convenient list structure which can contain vectors of
> various nature (numeric, character, factor, logical, ...)
> and looks quite similar to Excel table.
>
> matrix is a vector with (2) dimensions but as it is a vector it can not
> consist from objects of different nature (class). Therefore you can have
> numeric or character matrix but not numeric and character columns in your
> matrix.
>
> and vector is vector (numeric, character, logical,  ...) but again you can
> not mix items of different class in one vector.
>

of course it is. I forgot to say that the way I proposed works only if
the data-frame contains numeric objects only.

R is a great tool because you can get to the very same results in many
different ways.
Depending on the problem you're dealing with, you have to choose the
most efficient one.
Often, in my research work, the most efficient is the one that use as
less as possible lines of code:

Suppose a is a data.frame which contains numeric objects only

a <- data.frame(matrix(rnorm(100),10)) # some data

## 1 not very nice
b <- 0
for (j in 1:length(a)) b<-c(b,as.numeric(a[i]))
b<-b[-1]

## 2 long time ago I was a fortran guy
b<-numeric(length(a))
for (j in 1:dim(a)[2]){
  for (i in 1:dim(a)[1]){
     b[10*(j-1)+i] <- as.numeric(a[i,j])
  }
}

## 3 better: sapply function
as.numeric(sapply(a,function(x)as.numeric(x)))

## 4 shorter
as.numeric(as.matrix(a))

## which type of data a has
a <- data.frame(a,fact=sample(c('F1','F2'),dim(a)[1],replace=T))
class_a <- sapply(a,function(x)class(x))
class_a
a_numeric <- a[,class_a=='numeric']
as.numeric(as.matrix(a_numeric))

Regards,

PF

-- 
+-----------------------------------------------------------------------
| Patrizio Frederic,
| http://www.economia.unimore.it/frederic_patrizio/
+-----------------------------------------------------------------------



More information about the R-help mailing list