Visualizzazione post con etichetta string. Mostra tutti i post
Visualizzazione post con etichetta string. Mostra tutti i post

lunedì 15 settembre 2008

Fitting text under a plot

This is, REALLY, a basic tip, but, since I struggled for some time to fit long labels under a barplot I thought to share my solution for someone else's benefit.

As you can see (first image) the labels can not be displayed entirely:

counts <- sample(c(1000:10000),10)
labels <-list()
for (i in 1:10) { labels[i] <- paste("very long label number ",i,sep="")}
barplot( height=counts, names.arg=labels, horiz=F, las=2,col="lightblue", main="Before")


The trick to fit text of whatever dimension is to use the parameter mar to control the margins of the plot.

from ?par:

'mar' A numerical vector of the form 'c(bottom, left, top, right)'
which gives the number of lines of margin to be specified on
the four sides of the plot. The default is 'c(5, 4, 4, 2) + 0.1'.


op <- par(mar=c(11,4,4,2)) # the 10 allows the names.arg below the barplot
barplot( height=counts, names.arg=labels, horiz=F, las=2,col="skyblue", main="After")
rm(op)

mercoledì 20 giugno 2007

String manipulation, insert delim

From the list, as usual:

I want to be able to insert delimiters, say commas, into a string
of characters at uneven intervals such that:

foo<-c("haveaniceday")# my string of character
bar<-c(4,1,4,3) # my vector of uneven intervals
my.fun(foo,bar) # some function that places delimiters appropriately
have,a,nice,day # what the function would ideally return


1)

paste(read.fwf(textConnection(foo), bar, as.is = TRUE), collapse = ",")
[1] "have,a,nice,day"


2)

my.function <- function(foo, bar){
# construct a matrix with start/end character positions
start <- head(cumsum(c(1, bar)), -1) # delete last one
sel <- cbind(start=start,end=start + bar -1)
strings <- apply(sel, 1, function(x) substr(foo, x[1], x[2]))
paste(strings, collapse=',')
}

my.function(foo, bar)
[1] "have,a,nice,day"

mercoledì 16 maggio 2007

How can I turn a string into a variable?

If you have

varname <- c("a", "b", "d")

you can do

get(varname[1]) + 2

for a + 2

or

assign(varname[1], 2 + 2)

for a <- 2 + 2

or

eval(substitute(lm(y ~ x + variable), list(variable = as.name(varname[1]))

for lm(y ~ x + a)

At least in the first two cases it is often easier to just use a list, and then you can easily index it by name

vars <- list(a = 1:10, b = rnorm(100), d = LETTERS) vars[["a"]]

without any of this messing about.