This is a test version of Biostars. For the public version, visit https://www.biostars.org.
R multiple parameters

I m using vioplot R library to generate violon plot. How can I avoid the following stupid code with a loop or something else. ( the number of arguments to use should be random. In the following code it's 15 )

otu = otu_table(varBiom)
x1 = as.vector(otu[1,])
x2 = as.vector(otu[2,])
x3 = as.vector(otu[3,])
x4 = as.vector(otu[4,])
x5 = as.vector(otu[5,])
x6 = as.vector(otu[6,])
x7 = as.vector(otu[7,])
x8 = as.vector(otu[8,])
x9 = as.vector(otu[9,])
x10 = as.vector(otu[10,])
x11 = as.vector(otu[11,])
x12 = as.vector(otu[12,])
x13 = as.vector(otu[13,])
x14 = as.vector(otu[14,])
x15 = as.vector(otu[15,])

vioplot(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15)
r parameter code

What is your final plot like? Why are you passing 15 vectors to vioplot? Can't you pass individual vectors and use lapply / sapply, something like

sapply(otu, vioplot)

And most importantly, what is the output of str(otu)

Or an apply function for the call to as.vector().

I would like the following plot : https://framapic.org/h304KZZBwDGG/Y75ElIRvkvze.png each x[1..15] is a vector of numeric value .

vioplot takes as argument x and "..." for additional data vectors.

This is a limitation of the way vioplot is written. I remember years ago editing its source to accept a list of vectors. Sorry I don't have it to share, I just remember there was no function you're looking for. In plain R you could have multiple single plots with par(mfrow) and a loop. Because it accepts the ..., editing vioplot was not tricky, and the source is available.

2 answers

better ask on generic R questions on stackoverflow or the R mailing list and include a simply reproducible input. I would switch to ggplot2 where you plot from a "long" data frame - each observation in its own row.

library("reshape2")
library("ggplot2")
library("phyloseq")

data(GlobalPatterns)
otu <- as.data.frame(otu_table(GlobalPatterns))[1:15,]
otu$taxon <- rownames(otu)
otu.m <- melt(otu, id.vars="taxon")
ggplot(otu.m, aes(x=taxon,y=value)) + geom_violin()

Thanks ! It's not so pretty than vioplot , but I would be able to customize it I guess... Even if ggplot2 looks black magic for me :D

I think I found a way with meta programming. The following line works :

   otu = otu_table(varBiom)
   arguments= list()
   for (i in 1:15)
   {
     arguments[[i]] = as.vector(otu[i,])
   }

  do.call("vioplot", arguments)

Oh that's really nice!

I renamed to clarify.

arguments[[NUMBER]] are positionnal arguments : function(a,b,c .. ) arguments[[STRING]] are named arguments : function(color="red")

Log in to answer this question.