Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a dataframe into an array in R?

I am interested in calculate the medians of a data.frame. I found two approaches to do it: 1) with tapply and 2) with aggregate.

For many reasons, I am more interested in the "aggregate approach". However, since it gives me a data.frame and I need an array, I need to transform it. I found that there is a function that tries to do this (simply2array) but it doesn’t give me exactly an array.

Here is my example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When I try to calculate the median with tapply, it gives me an array

 df_median2 <- tapply(mtcars$mpg, mtcars$gear, median)
    > class(df_median2)
    [1] "array"

However, I need to use aggregate, which gives me a dataframe. In the following code, I tried to change it as much as I can to transform it into an array (without success)

df_median <- aggregate(mtcars$mpg ~ mtcars$gear, FUN=median) 
df_median <- as.data.frame(t(df_median))
names(df_median) <- df_median[1,]
df_median <- df_median[-1,]
rownames(df_median) <- "mpg"

my_array <- simplify2array(df_median)
> class(my_array)
[1] "numeric"

So… my question is, do you know if it is possible to convert a data.frame into an array in R?

Thanks very much in advance

Regards

>Solution :

The simplest way is to use this:

array(unlist(df_median))

If you want to include colnames you can use the dimnames = parameter in array()

If you also want to include the rownames you have to provide both the dimnames = and dim = parameter in array()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading