-3

I used RNCEP backstage to get a reanalyses data for temp. My data looks something like this:

(DD1 <- array(1:12, dim = c(2, 3, 2), 
              dimnames = list(c("A", "B"), 
                              c("a", "b", "c"), 
                              c("First", "Second"))))
# , , First
# 
#   a b c
# A 1 3 5
# B 2 4 6
# 
# , , Second
# 
#   a  b  c
# A 7  9 11
# B 8 10 12  

str(DD1)
#  int [1:2, 1:3, 1:2] 1 2 3 4 5 6 7 8 9 10 ...
#  - attr(*, "dimnames")=List of 3
#   ..$ : chr [1:2] "A" "B"
#   ..$ : chr [1:3] "a" "b" "c"
#   ..$ : chr [1:2] "First" "Second"

I think this is a tabular data?

I need to write the data as csv file where I have something like this:

y  a  a  b  b  c  c
x  A  B  A  B  A  B
   1  2  3  4  5  6
   7  8  9 10 11 12 

But when I used write.csv I got this:

write.csv(DD1)
# "","a.First","b.First","c.First","a.Second","b.Second","c.Second"
# "A",1,3,5,7,9,11
# "B",2,4,6,8,10,12 

I thought I had to transpose the data first. So I used this:

DD2 <- as.data.frame.table(DD1)

I also used t() but that also did not work.

A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
Moore
  • 129
  • 2
  • 11
  • 4
    It's useless to post the outputs of `Show` or `str`. Use `dput` – etienne Nov 24 '15 at 14:59
  • 2
    Please learn how to [format your question text](http://stackoverflow.com/editing-help) – Jaap Nov 24 '15 at 15:05
  • 1
    Do not post your data as an image, learn how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610) – Jaap Nov 24 '15 at 15:26

2 Answers2

3

Transpose function in R is t(), so hopefully this will work on the dataframe you are trying to transpose.

DD3= t(DD2)
ephackett
  • 249
  • 1
  • 15
1

You were on the right track with as.data.frame.table(DD1). That would give you a "long" dataset, that can then be converted to a "wide" form that you can use write.csv on.

Note, however, that R only allows one row of headers, so you will have to combine what you show as "x" and "y" into a single header row.

Here's the approach I would suggest:

library(data.table)
(DD2 <- dcast(data.table(as.data.frame.table(DD1)), 
              Var3 ~ Var1 + Var2, value.var = "Freq"))
#      Var3 A_a A_b A_c B_a B_b B_c
# 1:  First   1   3   5   2   4   6
# 2: Second   7   9  11   8  10  12

You can then easily use write.csv on the "DD2" object.

A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485