Sihem Sih
Sihem Sih

Reputation: 131

data.frame in R

I am a beginner in R, and I want to create an xlsx file from R. My data frame is defined as:

SP : List of 8
 $ WL          : num [1:1201] 200 200 201 202 202 ...
 $ t           : num [1:872, 1] 0.499 0.999 1.499 1.999 2.499 ...
 $ SP          : int [1:872, 1:1201, 1] 380 405 447 431 419 436 439 434 422 447 ...
 $ TF          : int [1:872, 1] 0 1 2 3 4 5 6 7 8 9 ...
 $ SpectraCount: num 872
 $ TStamp      : chr "12/01/2011 03:09:32PM"
 $ IT          : int 100
 $ SourceCount : num 1 

I want to transform the data.frame into a table with one column for each value of WL, and one row for each value of t, with the values inside the table as the SP for that combination of WL and t. The resulting table would look like:

               WL 1,.......... 1201
            t
            1         (SP values)
            .
            827

If i put

write.csv(SP1, file="SP1.csv", row.names = FALSE)

then i have Error in data.frame(WL = c(200, 200.5, 201, 201.5, 202, 202.5, 203, 203.5, : arguments imply differing number of rows: 1201, 872, 1

Upvotes: 1

Views: 714

Answers (2)

themel
themel

Reputation: 8895

No Excel interface I know of can deal with ragged lists - you will need to convert that to a rectangular data structure.

You could of course loop over the columns of your list and write those, but I think you'd be better off just padding your list into a data.frame:

> l <- list(a="foo", b=c(1,2,3), d=(1.0,2.0,3.0,4.0))
> rows <- max(unlist(lapply(l, length)))
> padded <- lapply(l, function(col) c(col, rep(NA, rows-length(col))))
> as.data.frame(padded)
     a  b d
1  foo  1 1
2 <NA>  2 2
3 <NA>  3 3
4 <NA> NA 4

Then, you can use any of the Excel packages, with my favourite XLConnect:

> library(XLConnect)
> writeWorksheetToFile(file="out.xlsx", data=as.data.frame(padded), sheet="Output")

Upvotes: 1

Romain Francois
Romain Francois

Reputation: 17642

Maybe generating a csv file would be enough. Excel can read csv files. See write.csv for this.

Otherwise, there is write.xls from the dataframes2xls package, or write.xlsx from the xlsx package.

Upvotes: 1

Related Questions