Home > Blockchain >  How to convert a dataframe into an array in R?
How to convert a dataframe into an array in R?

Time:11-05

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:

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

CodePudding user response:

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()

  • Related