strv7 strv7 - 2 months ago 5
R Question

How do I convert an array to a wide data frame in R?

Let's say I have an array

arr = as.array(c(1.1,0.5,3.2,4.3,5.5,6.3,0.4))


I want to convert this into a data frame so I try:

df = as.data.frame(arr)


But this gives me a data frame with nrows = 7 and ncols = 1. I need a data frame with nrows = 1 and ncols = 7. I have tried doing
t(df)
but that would return a matrix.

I know there has to be a simple way to do this... thank you!

Answer

How about:

arr = array(c(1.1,0.5,3.2,4.3,5.5,6.3,0.4), dim = c(1, 7))
as.data.frame(arr)

#   V1  V2  V3  V4  V5  V6  V7
#1 1.1 0.5 3.2 4.3 5.5 6.3 0.4

Note, use array or matrix, not as.array or as.matrix.


alistaire mentioned a good way

as.data.frame(t(c(1.1,0.5,3.2,4.3,5.5,6.3,0.4)))

#   V1  V2  V3  V4  V5  V6  V7
#1 1.1 0.5 3.2 4.3 5.5 6.3 0.4

which will transform the dim for you automatically.

Comments