[R] tranform a table?

David Hajage dhajage at gmail.com
Thu Sep 10 16:59:17 CEST 2009


I think you could use reshape and ascii package here.

Create a file ("code.Rnw") with this code :

John and Jane
=============

<<>>=
df <- data.frame(names = c("John", "Jane"), field1 = c("value1", "value2"),
field2 = c("value3", "value4"))
library(reshape)
cdf <- cast(melt(df, id = "names"), variable ~ . | names)
@

<<results=ascii>>=
library(ascii)
ascii(cdf$Jane)
ascii(cdf$John)
@

Then from R, run :
Sweave("code.Rnw", RweaveAsciidoc)

Finally, use asciidoc <http://www.methods.co.nz/asciidoc/> to convert the
new file "code.txt" into html :
asciidoc code.txt

David


On Thu, Sep 10, 2009 at 15:10, bbimber <bimber at wisc.edu> wrote:

>
> hello everyone,
>
> i'm new to R, so i hope you dont mind a fairly basic R question.  we're
> using R to manipulate the results of SQL queries and create an HTML output.
> I'm starting with a table that looks essentially like this:
>
> Name    Field1     Field2
> John      value1     value2
> Jane      value3     value4
>
> My table is stored as a dataframe.  I'd like to efficiently produce an
> output that iterates through each row, transposes it and outputs an HTML
> table (one per row).  like this:
>
> Name: John
> Field1: value1
> Field2: value2
>
> Name: Jane
> Field1: value3
> Field2: value4
>
> I can accomplish this by looping through each row, then outputting that
> row's table.  This gets the job done, but it seems there must be a better
> way.  I'm going to need to do this sort of conversion a lot,
> so the simpler the better.  is there a better way to approach it than the
> code below?  is there a more general term for the sort of transformation
> i'm
> trying to make that might help guide my searching?
>
> i realize i need to look into better methods of outputting HTML tables
> (like
> r2html).
>
> here's the basic idea.  'labkey.data' is the data frame produced by my SQL
> query:
>
> D<-labkey.data
> H<-colnames(D)
> T<-t(D)
> L<-length(D$id)
>
> output <- ""
>
> for(i in 1:L) {
> R<-my.row <- D[i, ]
> R<-t(R)
> Len<-length(R)
>
> output <- paste(output, "<table border=0>")
> for(j in 1:Len) {
> output <- paste(output,"<tr><td>", H[j],":</td><td>", R[j], "</td>")
> }
>
> output <- paste(output, "</table><p>")
>
> }
>
> write(output, file="${htmlout:output}")
>
> Thanks for any help.
> --
> View this message in context:
> http://www.nabble.com/tranform-a-table--tp25382806p25382806.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>


More information about the R-help mailing list