gtwebb
gtwebb

Reputation: 3011

R writing an array to a file

I'm trying to get some data out of R and am having trouble.

I don't fully grasp the different data types and how to convert between them. Basically I want to use tapply to get a summary and then write the output to a file. The function works fine but I can't get the output that I want.

The problem is shown in the code below and is caused

my.df<-data.frame(sort=c(rep("a",10),rep("b",10)),value=seq(1,20,1))

my.array<-tapply(my.df$value,my.df$sort,summary)
my.array

#These don't work

The output I would like to get to a file is something like this

    Min 1st Qu  Median  Mean    3rd Qu. Max
a   1   3.25    5.5     5.5     7.75    10
b   11  13.25   15.5    15.5    17.75   20

Some things I've tried are:

my.array<-tapply(my.df$value,my.df$sort,summary)
my.array

write.csv(my.array,file="b.csv")
write.csv(sHmin_summary,file="SHmin_summary.csv")

    Min 1st Qu  Median  Mean    3rd     Qu. Max
a   1   3.25    5.5     5.5     7.75    10
b   11  13.25   15.5    15.5    17.75   20

write(my.array,file="temp.txt")
write.csv(my.array,file="temp.csv")
#doesn't work

b<-do.call(rbind.data.frame,my.array)
b
#Close but the header names are wrong, I could correct manually but there should be a better way

b<-matrix(unlist(my.array),ncol=2)
b
#Loses headers and rows

What I'm thinking is pulling the names out of the first list and apply them to the dataframe created with rbind or start with the first list item and them rbind onto that and hopefully the names will stay.

Any advice would be appreciated.

Gordon

Upvotes: 4

Views: 7565

Answers (1)

Aaron - mostly inactive
Aaron - mostly inactive

Reputation: 37734

You're close. Use just rbind not rbind.data.frame to keep the names properly, as the elements of my.array aren't data frames.

Upvotes: 1

Related Questions