Format to wiki table.r

From Bioinformatikpedia

In R, read in the code:

source("/mnt/home/student/schillerl/MasterPractical/format_to_wiki_table.r")

and then call the function make_wiki_table() as described in the script below.

#---------------------------------------------------------------------------------------------------------
#
# Change table to wiki format.
#
# Author: Laura Schiller
#
#---------------------------------------------------------------------------------------------------------
# Usage: 
# make_wiki_table(<in>, <out>)
# or make_wiki_table(<in>, <out>, <sep>, <format>)
# in:     input file path (input file contains table with header)
# out:    output file path
# sep:    separator used in input table file (e. g. "\t", ";" or ","), 
#         default white space (i. e. one or more spaces, tabs...)
# format: formatting options that should be added to wiki table header,
#         default none
#---------------------------------------------------------------------------------------------------------
# example for usage:
# make_wiki_table("table.csv", "wiki_table.txt", ";", "class='wikitable' border='1' style='width:300px'")
#---------------------------------------------------------------------------------------------------------

make_wiki_table <- function(in_path, out_path, separator = "", format = "") {
	dat <- read.table(in_path, header = T, sep = separator)
	out_lines <- c()

	out_lines <- rbind(out_lines, paste("{| ", format, sep = ""))
	header_line <- paste("! ", names(dat)[1], sep = "")
	if (dim(dat)[2] > 1) {
		for (i in 2:dim(dat)[2]) {
			header_line <- paste(header_line, " !! ", names(dat)[i], sep = "")
		}
	}
	out_lines <- rbind(out_lines, header_line)
	if (dim(dat)[1] > 0) {
		for (i in 1:dim(dat)[1]) {
			out_lines <- rbind(out_lines, "|-")
			line <- paste("| ", dat[i, 1], sep = "")
			if (dim(dat)[2] > 1) {
				for (j in 2:dim(dat)[2]) {
					line <- paste(line, " || ", dat[i, j], sep = "")
				}
			}
			out_lines <- rbind(out_lines, line)
		}
	}
	out_lines <- rbind(out_lines, "|}")

	out_file <- file(out_path)
	writeLines(out_lines, out_file)
	close(out_file)
}