1

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!

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
strv7
  • 109
  • 10

2 Answers2

3

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.

Community
  • 1
  • 1
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
  • `arr` is an array, not a vector. `as.data.frame.list(arr)` will put an array into wide form directly, though that's somewhat inexplicable. – alistaire Sep 16 '16 at 02:58
3

If we need 7 column dataset, we can use as.data.frame.list on a vector

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

As @ZheyuanLi mentioned the above will append "X" as prefix for the column names. We can change the column names in the col.names argument

as.data.frame.list(c(1.1,0.5,3.2,4.3,5.5,6.3,0.4), col.names = paste0("V", 1:7))

Or another option would be to have names for the vector elements

as.data.frame.list(setNames(c(1.1,0.5,3.2,4.3,5.5,6.3,0.4), paste0("V", 1:7)))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    This option ----> as.data.frame.list(setNames(c(1.1,0.5,3.2,4.3,5.5,6.3,0.4), paste0("V", 1:7))) <----- worked for me! Thanks! – strv7 Sep 16 '16 at 07:31
  • I might have an older version of R installed in the database since this ---> as.data.frame.list(c(1.1,0.5,3.2,4.3,5.5,6.3,0.4), col.names = paste0("V", 1:7)) <----- did not change the column names – strv7 Sep 16 '16 at 07:36
  • @strv7 I am using R 3.3.0 – akrun Sep 16 '16 at 10:07