[R] Why does the print method fail for very small numbers?

2022-02-17 Thread Marius Hofert
Dear expeRts,

I'm familiar with IEEE 754. Is there an easy way to explain why even
just printing of small numbers fails?

1e-317 # 1e-317 => fine
1e-318 # 9.87e-319 => gets tricky; seems to call print() => as.character() 
=> format() => paste()
1e-318 == 9.87e-319 # TRUE
2.48e-324 # prints 4.940656e-324 for me
2.48e-324 == 4.940656e-324 # TRUE
## Relative error as a plot
rel_error <- function(x)
plot(abs((as.numeric(as.character(x)) - x) / x), type = "l",
 ylab = "Relative error between x and as.numeric(as.character(x))")
rel_error(seq(0.001, 0.001 + .Machine$double.xmin, length.out = 1001)) # fine
rel_error(seq(0, .Machine$double.xmin, length.out = 1001)) # printing breaks 
down

Of course, [0,.Machine$double.xmin] is somewhat of a strange set of numbers to 
consider,
and I expect things like "==" to be easily fooled there, but already the print 
method (?)

Thanks & cheers,
Marius

sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: x86_64-apple-darwin21.2.0 (64-bit)
Running under: macOS Monterey 12.1
...


__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


Re: [R] R_BATCH_OPTIONS not respected?

2019-09-10 Thread Marius Hofert
On Tue, Sep 10, 2019 at 12:38 PM Martin Maechler
 wrote:
>
> >>>>> Marius Hofert
> >>>>> on Mon, 9 Sep 2019 22:38:38 +0200 writes:
>
> > Hi,
> > I typically start R with "--no-restore --no-save" (to avoid .RData
> > files being written) and would like to have the same behavior under 'R
> > CMD BATCH'. I use R_BATCH_OPTIONS="--no-restore --no-save" in my
> > ~/.Renviron but running an R script with 'R CMD BATCH' still produces
> > a .RData file. What's the correct way of getting the '--no-restore
> > --no-save' options when in batch mode?
>
> > (This is on macOS 10.14.6 with R version 3.6.1)
>
> Maybe macOS is the problem?
>
> It works fine on Linux:
>
> export R_BATCH_OPTIONS='--no-save --no-restore'
> R CMD BATCH .R

Hoi Martin,

Thanks for helping. This also works for me, but not if I put
R_BATCH_OPTIONS="--no-restore --no-save" in ~/.Renviron.
If I have an R script called MWE.R containing
print(Sys.getenv("R_BATCH_OPTIONS")), I correctly see "--no-restore
--no-save"
being printed to .Rout, but still obtain .RData. (I also think this is
a macOS problem, but couldn't figure it out yet).

Cheers,
M

>
> produces  .Rout and nothing else  for me
>
>
> Martin
>
> > Thanks & cheers,
> > M
>
> > __
> > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > 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.

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


[R] R_BATCH_OPTIONS not respected?

2019-09-09 Thread Marius Hofert
Hi,

I typically start R with "--no-restore --no-save" (to avoid .RData
files being written) and would like to have the same behavior under 'R
CMD BATCH'. I use R_BATCH_OPTIONS="--no-restore --no-save" in my
~/.Renviron but running an R script with 'R CMD BATCH' still produces
a .RData file. What's the correct way of getting the '--no-restore
--no-save' options when in batch mode?

(This is on macOS 10.14.6 with R version 3.6.1)

Thanks & cheers,
M

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


[R] How to create the/an integer 'seed' for set.seed() from a given .Random.seed?

2019-07-20 Thread Marius Hofert
Hi,

1) Given .Random.seed, how can one compute *the* integer 'seed' such
that set.seed(seed) generates .Random.seed?
2) If 1) is not possible, how can one compute *an* integer 'seed' from
a given .Random.seed such that different .Random.seed's are guaranteed
to give different integers 'seed' (or at least with a very high
probability)? In other words, how can one construct an injective
function from .Random.seed objects to an integer?

(In an ideal world, this would work for all kinds of random number generators).

What I found out (... is not very much so far):
./src/main/names.c -> do_setseed() -> RNG.c -> RNG_Init() leads to (at
least for the Mersenne Twister)...
for(j = 0; j < RNG_Table[kind].n_seed; j++) {
seed = (69069 * seed + 1);
RNG_Table[kind].i_seed[j] = seed;
}
FixupSeeds(kind, 1);
... which gives some hope that the first entry in RNG_Table can be
used to access 'seed' (which could be the 3rd value of .Random.seed in
this case, but I'm not sure...).

Background (or 'why on earth would you...'): I have a function myRNG
of the following form (body explains the non-minimal problem):
myRNG <- function(n, method, ...) {
  if(method = "A") {
  
  } else {
  
  }
}

Thanks & cheers,
Marius

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


Re: [R] How to test existence of an environment and how to remove it (from within functions)?

2016-08-30 Thread Marius Hofert
Hi Duncan,

... I don't have to know (I thought). The idea was to set up the environment
only for a single object x. If it (= the environment (see MWE 2) *or* the object
(see MWE 1)) exists, it's the right one. But I agree that it's 'cleaner' to work
with a hash -- yet I first wanted to understand how to check whether the
environment exists and how to remove it (especially for the latter, I couldn't
find anything... most sources of information dealt with how to delete objects in
an environment, not an environment itself [caution: I just started to learn
about environments, there is a high chance that there's a misconception on my
end...:-) ]).

With memoise, it works as expected:

library(memoise)

## Auxiliary function
aux <- function(x) {
Sys.sleep(1)
x[,1:2]
}

## Main function
main <- function() {
aux. <- memoise(aux)
x <- matrix(rnorm(100*1000), ncol = 1000)
res <- replicate(5, aux.(x))
forget(aux.)
res
}

## Testing
set.seed(271)
system.time(res1 <- main()) # => ~ 1s
stopifnot(all.equal(res1[,,1], res1[,,2]),
  all.equal(res1[,,2], res1[,,3]),
  all.equal(res1[,,3], res1[,,4]),
  all.equal(res1[,,4], res1[,,5]))
system.time(res2 <- main()) # => ~ 1s
stopifnot(all.equal(res2[,,1], res2[,,2]),
  all.equal(res2[,,2], res2[,,3]),
  all.equal(res2[,,3], res2[,,4]),
  all.equal(res2[,,4], res2[,,5]))

The biggest takeaway here is to have main() set up another auxiliary function
(aux.()) which calls aux().

I looked at memoise and it is surprisingly short. I then tried to adapt the idea
directly (I try to learn things, not just use them), but it fails with "Error in
exists(hash, envir = cache, inherits = FALSE) (from #6) : use of NULL
environment is defunct". Not sure why this works from inside memoise...


library(digest)

## Auxiliary function
aux <- function(x) {
Sys.sleep(1)
x[,1:2]
}

## Main function
main <- function() {

## Wrap aux() in another helper function
aux. <- function(...) {
## Set up cache
cache <- NULL
cache_reset <- function() cache <<- new.env(TRUE, emptyenv())
## Define key
hash <- digest(list(...))
## Do the computation (if not done already)
if (exists(hash, envir = cache, inherits = FALSE)) {
get(hash, envir = cache, inherits = FALSE) # get result
} else {
res <- aux(...) # compute result
assign(hash, res, envir = cache) # cache result
res
}
}

## Call aux() via aux.()
x <- matrix(rnorm(100*1000), ncol = 1000)
res <- replicate(5, aux.(x))

## Reset cache
get("cache", environment(aux.))$reset()

## Return
res
}

## Testing
set.seed(271)
system.time(res1 <- main())
## => Error in exists(hash, envir = cache, inherits = FALSE) (from #6) :
##  use of NULL environment is defunct


Thanks & cheers,
Marius

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


Re: [R] How to test existence of an environment and how to remove it (from within functions)?

2016-08-29 Thread Marius Hofert
Dear Duncan,

Thanks a lot for your help.

I tried to adapt your example to my MWE, but the subsequent calls of
main() are 'too fast' now: new calls of main() should also 'reset' the
environment (as a different x is generated then), that's why I tried
to remove the environment .my_environ from within main():

## Auxiliary function with caching
aux <- local({
.my_environ <- new.env(hash = FALSE, parent = emptyenv()) # define
the environment
function(x) {
## Setting up the environment and caching
if(exists("cached.obj", envir = .my_environ)) { # look-up (in
case the object already exists)
x.cols <- get("cached.obj", .my_environ)
} else { # time-consuming part (+ cache)
x.cols <- split(x, col(x))
Sys.sleep(1)
assign("cached.obj", x.cols, envir = .my_environ)
}
## Do something with the result from above (here: pick out two randomly
## chosen columns)
x.cols[sample(1:1000, size = 2)]
}
})

## Main function
main <- function() {
x <- matrix(rnorm(100*1000), ncol = 1000)
res <- replicate(5, aux(x))
rm(.my_environ) # TODO: Trying to remove the environment
res
}

## Testing
set.seed(271)
system.time(main()) # => ~ 1s since the cached object is found
system.time(main()) # => ~ 0s (instead of ~ 1s)
system.time(main()) # => ~ 0s (instead of ~ 1s)

Do you know a solution for this?

Background information:
This is indeed a problem from a package which draws many (sub)plots
within a single plot. Each single (sub)plot needs to access the data
for plotting but does not known about the other (sub)plots... Thought
this might be interesting in general for caching results.

Thanks & cheers,
Marius



On Mon, Aug 29, 2016 at 7:59 PM, Duncan Murdoch
 wrote:
> On 29/08/2016 1:36 PM, Marius Hofert wrote:
>> Hi,
>>
>> I have a function main() which calls another function aux() many times. aux()
>> mostly does the same operations based on an object and thus I would like it 
>> to
>> compute and store this object for each call from main() only once.
>>
>> Below are two versions of a MWE. The first one computes the right result 
>> (but is
>> merely there for showing what I would like to have; well, apart from the
>> environment .my_environ still floating around after main() is called).
>> It works with an
>> environment .my_environ in which the computed object is stored. The
>> second MWE tries to set
>> up the environment inside aux(), but neither the check of existence in
>> aux() nor the
>> removal of the whole environment in main() work (see 'TODO' below). How can 
>> this
>> be achieved?
>>
>
> If you create aux in a local() call, it can have persistent storage,
> because local() creates an environment to hold it.  For example,
>
> aux <- local({
>persistent <- NULL
>function(x) {
>  if (!is.null(persistent))
>message("Previous arg was ", persistent)
>  persistent <<- x
>}
> })
>
> Note that the assignment uses <<- to work in the local-created
> environment rather than purely locally within the evaluation frame of
> the call.  You need to create the variable "persistent" there, or the
> assignment would go to the global environment, which is bad.
>
> This gives
>
>  > aux(1)
>  > aux(2)
> Previous arg was 1
>  > aux(3)
> Previous arg was 2
>
> Duncan Murdoch
>
>> Cheers,
>> Marius
>>
>>
>> ### Version 1: Setting up the environment in .GlobalEnv 
>> 
>>
>> .my_environ <- new.env(hash = FALSE, parent = emptyenv()) # define the
>> environment
>>
>> ## Auxiliary function with caching
>> aux <- function(x) {
>> ## Setting up the environment and caching
>> if(exists("cached.obj", envir = .my_environ)) { # look-up (in case
>> the object already exists)
>> x.cols <- get("cached.obj", .my_environ)
>> } else { # time-consuming part (+ cache)
>> x.cols <- split(x, col(x))
>> Sys.sleep(1)
>> assign("cached.obj", x.cols, envir = .my_environ)
>> }
>> ## Do something with the result from above (here: pick out two randomly
>> ## chosen columns)
>> x.cols[sample(1:1000, size = 2)]
>> }
>>
>> ## Main function
>> main <- function() {
>> x <- matrix(rnorm(100*1000), ncol = 1000)
>> res <- replicate(5, aux(x))
>> rm(cached.obj, envir = .my_environ) # only removing the *object*
>> (but not the environment)

[R] How to test existence of an environment and how to remove it (from within functions)?

2016-08-29 Thread Marius Hofert
Hi,

I have a function main() which calls another function aux() many times. aux()
mostly does the same operations based on an object and thus I would like it to
compute and store this object for each call from main() only once.

Below are two versions of a MWE. The first one computes the right result (but is
merely there for showing what I would like to have; well, apart from the
environment .my_environ still floating around after main() is called).
It works with an
environment .my_environ in which the computed object is stored. The
second MWE tries to set
up the environment inside aux(), but neither the check of existence in
aux() nor the
removal of the whole environment in main() work (see 'TODO' below). How can this
be achieved?

Cheers,
Marius


### Version 1: Setting up the environment in .GlobalEnv 

.my_environ <- new.env(hash = FALSE, parent = emptyenv()) # define the
environment

## Auxiliary function with caching
aux <- function(x) {
## Setting up the environment and caching
if(exists("cached.obj", envir = .my_environ)) { # look-up (in case
the object already exists)
x.cols <- get("cached.obj", .my_environ)
} else { # time-consuming part (+ cache)
x.cols <- split(x, col(x))
Sys.sleep(1)
assign("cached.obj", x.cols, envir = .my_environ)
}
## Do something with the result from above (here: pick out two randomly
## chosen columns)
x.cols[sample(1:1000, size = 2)]
}

## Main function
main <- function() {
x <- matrix(rnorm(100*1000), ncol = 1000)
res <- replicate(5, aux(x))
rm(cached.obj, envir = .my_environ) # only removing the *object*
(but not the environment)
res
}

## Testing
set.seed(271)
system.time(main()) # => ~ 1s since the cached object is found


### Version 2: Trying to set up the environment inside aux() ###

## Auxiliary function with caching
aux <- function(x) {
## Setting up the environment and caching
if(!exists(".my_environ", mode = "environmnent")) # TODO: How to
check the existence of the environment? This is always TRUE...
.my_environ <- new.env(hash = FALSE, parent = emptyenv()) #
define the environment
if(exists("cached.obj", envir = .my_environ)) { # look-up (in case
the object already exists)
x.cols <- get("cached.obj", .my_environ)
} else { # time-consuming part (+ cache)
x.cols <- split(x, col(x))
Sys.sleep(1)
assign("cached.obj", x.cols, envir = .my_environ)
}
## Do something with the result from above (here: pick out two randomly
## chosen columns)
x.cols[sample(1:1000, size = 2)]
}

## Main function
main <- function() {
x <- matrix(rnorm(100*1000), ncol = 1000)
res <- replicate(5, aux(x))
rm(.my_environ) # TODO: How to properly remove the environment?
res
}

## Testing
set.seed(271)
system.time(main()) # => ~ 5s since (the cached object in) environment
.my_environ is not found

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


Re: [R] How to split a data.frame into its columns?

2016-08-29 Thread Marius Hofert
Hi David and Jeff,

Thanks for your quick help, unclass() was precisely what I was looking for.

Cheers,
M

On Mon, Aug 29, 2016 at 10:39 AM, aditya pant  wrote:
>
> ^^ठश्रएइ),,,
> 
> From: David Winsemius
> Sent: ‎29-‎08-‎2016 11:59
> To: Marius Hofert
> Cc: R-help
> Subject: Re: [R] How to split a data.frame into its columns?
>
>
>> On Aug 28, 2016, at 11:14 PM, Marius Hofert 
>> wrote:
>>
>> Hi,
>>
>> I need a fast way to split a data.frame (and matrix) into a list of
>> columns.
>
> This is a bit of a puzzle since data.frame objects are by definition "lists
> of columns".
>
> If you want a data.frame object (say it's name is dat) to _only be a list of
> columns then
>
> dat <- unclass(dat)
>
> The split.data.frame function splits by rows since that is the most desired
> and expected behavior and because the authors of S/R probably thought there
> was no point in making the split "by columns" when it already was.
>
> --
> David.
>
>> For matrices, split(x, col(x)) works (which can then be done
>> in C for speed-up, if necessary), but for a data.frame? split(iris,
>> col(iris)) does not work as expected (?).
>> The outcome should be lapply(seq_len(ncol(iris)), function(j)
>> iris[,j]) and not require additional packages (if possible).
>>
>> Thanks & cheers,
>> Marius
>>
>> PS: Below is the C code for matrices. Not sure how easy it would be to
>> extend that to data.frames (?)
>>
>> SEXP col_split(SEXP x)
>> {
>>/* Setup */
>>int *dims = INTEGER(getAttrib(x, R_DimSymbol));
>>int n = dims[0], d = dims[1];
>>SEXP res = PROTECT(allocVector(VECSXP, d));
>>SEXP ref;
>>int i = 0, j, k;
>>
>>/* Distinguish int/real matrices */
>>switch (TYPEOF(x)) {
>>case INTSXP:
>>for(j = 0; j < d; j++) {
>>SET_VECTOR_ELT(res, j, allocVector(INTSXP, n));
>>int *e = INTEGER(VECTOR_ELT(res, j));
>>for(k = 0 ; k < n ; i++, k++) {
>>e[k] = INTEGER(x)[i];
>>}
>>}
>>break;
>>case REALSXP:
>>for(j = 0; j < d; j++) {
>>SET_VECTOR_ELT(res, j, allocVector(REALSXP, n));
>>double *e = REAL(VECTOR_ELT(res, j));
>>for(k = 0 ; k < n ; i++, k++) {
>>e[k] = REAL(x)[i];
>>}
>>}
>>break;
>>case LGLSXP:
>>for(j = 0; j < d; j++) {
>>SET_VECTOR_ELT(res, j, allocVector(LGLSXP, n));
>>int *e = LOGICAL(VECTOR_ELT(res, j));
>>for(k = 0 ; k < n ; i++, k++) {
>>e[k] = LOGICAL(x)[i];
>>}
>>}
>>break;
>>case STRSXP:
>>for(j = 0; j < d; j++) {
>> ref = allocVector(STRSXP, n);
>>SET_VECTOR_ELT(res, j, ref);
>>ref = VECTOR_ELT(res, j);
>>for(k = 0 ; k < n ; i++, k++) {
>>SET_STRING_ELT(ref, k, STRING_ELT(x, i));
>>}
>>}
>>break;
>>default: error("Wrong type of 'x': %s",
>> CHAR(type2str_nowarn(TYPEOF(x;
>>}
>>
>>/* Return */
>>UNPROTECT(1);
>>return(res);
>> }
>>
>> __
>> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> 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.
>
> David Winsemius
> Alameda, CA, USA
>
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.

[R] How to split a data.frame into its columns?

2016-08-28 Thread Marius Hofert
Hi,

I need a fast way to split a data.frame (and matrix) into a list of
columns. For matrices, split(x, col(x)) works (which can then be done
in C for speed-up, if necessary), but for a data.frame? split(iris,
col(iris)) does not work as expected (?).
The outcome should be lapply(seq_len(ncol(iris)), function(j)
iris[,j]) and not require additional packages (if possible).

Thanks & cheers,
Marius

PS: Below is the C code for matrices. Not sure how easy it would be to
extend that to data.frames (?)

SEXP col_split(SEXP x)
{
/* Setup */
int *dims = INTEGER(getAttrib(x, R_DimSymbol));
int n = dims[0], d = dims[1];
SEXP res = PROTECT(allocVector(VECSXP, d));
SEXP ref;
int i = 0, j, k;

/* Distinguish int/real matrices */
switch (TYPEOF(x)) {
case INTSXP:
for(j = 0; j < d; j++) {
SET_VECTOR_ELT(res, j, allocVector(INTSXP, n));
int *e = INTEGER(VECTOR_ELT(res, j));
for(k = 0 ; k < n ; i++, k++) {
e[k] = INTEGER(x)[i];
}
}
break;
case REALSXP:
for(j = 0; j < d; j++) {
SET_VECTOR_ELT(res, j, allocVector(REALSXP, n));
double *e = REAL(VECTOR_ELT(res, j));
for(k = 0 ; k < n ; i++, k++) {
e[k] = REAL(x)[i];
}
}
break;
case LGLSXP:
for(j = 0; j < d; j++) {
SET_VECTOR_ELT(res, j, allocVector(LGLSXP, n));
int *e = LOGICAL(VECTOR_ELT(res, j));
for(k = 0 ; k < n ; i++, k++) {
e[k] = LOGICAL(x)[i];
}
}
break;
case STRSXP:
for(j = 0; j < d; j++) {
ref = allocVector(STRSXP, n);
SET_VECTOR_ELT(res, j, ref);
ref = VECTOR_ELT(res, j);
for(k = 0 ; k < n ; i++, k++) {
SET_STRING_ELT(ref, k, STRING_ELT(x, i));
}
}
break;
default: error("Wrong type of 'x': %s", CHAR(type2str_nowarn(TYPEOF(x;
}

/* Return */
UNPROTECT(1);
return(res);
}

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


Re: [R] What's box() (exactly) doing?

2016-06-27 Thread Marius Hofert
On Mon, Jun 27, 2016 at 5:42 PM, Greg Snow <538...@gmail.com> wrote:
> You can use the grconvertX and grconvertY functions to find the
> coordinates (in user coordinates to pass to rect) of the figure region
> (or other regions).
>
> Probably something like:
> grconvertX(c(0,1), from='nfc', to='user')
> grconvertY(c(0,1), from='nfc', to='user')

Hi Greg,

Thanks, that's good to know.

Cheers,
Marius

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


Re: [R] What's box() (exactly) doing?

2016-06-24 Thread Marius Hofert
Hi Jim,

Here is a follow-up question: How would you replicate box("figure")
(instead of box() = box("plot"))?
I tried to fill the plotted box but there seems to be no argument to
box("figure") that does that. If that's indeed the case, one could
work again with rect() (thus replicating box("figure")), but how can
one specify the exact location/width/height of the rectangle? (see
example below)

Cheers,
M

plot(NA, type = "n", ann = TRUE, axes = TRUE, xlim = 0:1, ylim = 0:1)
box("figure", col = "red", lwd = 2) # how to fill?

par(xpd = TRUE)
width = 1.4 # obviously not correct...
height <- width
loc.x <- 0.5
loc.y <- 0.5
xleft <- loc.x-width/2
xright <- loc.x+width/2
ybottom <- loc.y-height/2
ytop <- loc.y+height/2
rect(xleft = xleft, ybottom = ybottom, xright = xright, ytop = ytop,
 col = adjustcolor("grey80", alpha.f = 0.5))
par(xpd = FALSE)

On Fri, Jun 24, 2016 at 8:40 PM, Marius Hofert
 wrote:
> Hi Jim,
>
> Thanks a lot, exactly what I was looking for.
>
> Cheers,
> Marius
>
>
>
> On Thu, Jun 23, 2016 at 11:06 PM, Jim Lemon  wrote:
>> Hi Marius,
>> There are a few things that are happening here. First, the plot area
>> is not going to be the same as your x and y limits unless you say so:
>>
>> # run your first example
>> par("usr")
>> [1] -0.04  1.04 -0.04  1.04
>>
>> # but
>> plot(NA, type = "n", ann = FALSE, axes = FALSE,
>>  xlim = 0:1, ylim = 0:1,xaxs="i",yaxs="i")
>> box()
>> rect(xleft = 0, ybottom = 0, xright = 1, ytop = 1, col = "grey80")
>> par("usr")
>> [1] 0 1 0 1
>>
>> Second, the "rect" function is automatically clipped to the plot area,
>> so you may lose a bit at the edges if you don't override this:
>>
>> par(xpd=TRUE)
>> rect(...)
>> par(xpd=FALSE)
>>
>> Finally your second example simply multiplies the first problem by
>> specifying a layout of more than one plot. Applying the "xaxs" and
>> "yaxs" parameters before you start plotting will fix this:
>>
>> par(xaxs="i",yaxs="i")
>>
>> Jim
>>
>> On Fri, Jun 24, 2016 at 12:29 PM, Marius Hofert
>>  wrote:
>>> Hi,
>>>
>>> I would like to replicate the behavior of box() with rect() (don't ask why).
>>> However, my rect()angles are always too small. I looked a bit into the
>>> internal C_box but
>>> couldn't figure out how to solve the problem. Below is a minimal
>>> working (and a slightly bigger) example.
>>>
>>> Cheers,
>>> Marius
>>>
>>> ## MWE
>>> plot(NA, type = "n", ann = FALSE, axes = FALSE, xlim = 0:1, ylim = 0:1)
>>> rect(xleft = 0, ybottom = 0, xright = 1, ytop = 1, col = "grey80") #
>>> should match box()
>>> box()
>>>
>>> ## Extended example
>>>
>>> ## Basic plot
>>> my_rect <- function()
>>> {
>>> plot(NA, type = "n", ann = FALSE, axes = FALSE, xlim = 0:1, ylim = 0:1)
>>> rect(xleft = 0, ybottom = 0, xright = 1, ytop = 1, col = "grey80")
>>> # should match box()
>>> box()
>>> }
>>>
>>> ## Layout
>>> lay <- matrix(0, nrow = 3, ncol = 3, byrow = TRUE)
>>> lay[1,1] <- 1
>>> lay[2,1] <- 2
>>> lay[2,2] <- 3
>>> lay[2,3] <- 4
>>> lay[3,3] <- 5
>>> layout(lay, heights = c(1, 10, 1), widths = c(10, 1, 10))
>>> layout.show(5) # => no space between rectangles; calls box() to draw the 
>>> boxes
>>>
>>> ## Fill layout
>>> par(oma = rep(0, 4), mar = rep(0, 4))
>>> my_rect()
>>> my_rect()
>>> my_rect()
>>> my_rect()
>>> my_rect()
>>> ## => spaces between rectangles => why?/how to avoid?
>>>
>>> __
>>> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
>>> 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.

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


Re: [R] What's box() (exactly) doing?

2016-06-24 Thread Marius Hofert
Hi Jim,

Thanks a lot, exactly what I was looking for.

Cheers,
Marius



On Thu, Jun 23, 2016 at 11:06 PM, Jim Lemon  wrote:
> Hi Marius,
> There are a few things that are happening here. First, the plot area
> is not going to be the same as your x and y limits unless you say so:
>
> # run your first example
> par("usr")
> [1] -0.04  1.04 -0.04  1.04
>
> # but
> plot(NA, type = "n", ann = FALSE, axes = FALSE,
>  xlim = 0:1, ylim = 0:1,xaxs="i",yaxs="i")
> box()
> rect(xleft = 0, ybottom = 0, xright = 1, ytop = 1, col = "grey80")
> par("usr")
> [1] 0 1 0 1
>
> Second, the "rect" function is automatically clipped to the plot area,
> so you may lose a bit at the edges if you don't override this:
>
> par(xpd=TRUE)
> rect(...)
> par(xpd=FALSE)
>
> Finally your second example simply multiplies the first problem by
> specifying a layout of more than one plot. Applying the "xaxs" and
> "yaxs" parameters before you start plotting will fix this:
>
> par(xaxs="i",yaxs="i")
>
> Jim
>
> On Fri, Jun 24, 2016 at 12:29 PM, Marius Hofert
>  wrote:
>> Hi,
>>
>> I would like to replicate the behavior of box() with rect() (don't ask why).
>> However, my rect()angles are always too small. I looked a bit into the
>> internal C_box but
>> couldn't figure out how to solve the problem. Below is a minimal
>> working (and a slightly bigger) example.
>>
>> Cheers,
>> Marius
>>
>> ## MWE
>> plot(NA, type = "n", ann = FALSE, axes = FALSE, xlim = 0:1, ylim = 0:1)
>> rect(xleft = 0, ybottom = 0, xright = 1, ytop = 1, col = "grey80") #
>> should match box()
>> box()
>>
>> ## Extended example
>>
>> ## Basic plot
>> my_rect <- function()
>> {
>> plot(NA, type = "n", ann = FALSE, axes = FALSE, xlim = 0:1, ylim = 0:1)
>> rect(xleft = 0, ybottom = 0, xright = 1, ytop = 1, col = "grey80")
>> # should match box()
>> box()
>> }
>>
>> ## Layout
>> lay <- matrix(0, nrow = 3, ncol = 3, byrow = TRUE)
>> lay[1,1] <- 1
>> lay[2,1] <- 2
>> lay[2,2] <- 3
>> lay[2,3] <- 4
>> lay[3,3] <- 5
>> layout(lay, heights = c(1, 10, 1), widths = c(10, 1, 10))
>> layout.show(5) # => no space between rectangles; calls box() to draw the 
>> boxes
>>
>> ## Fill layout
>> par(oma = rep(0, 4), mar = rep(0, 4))
>> my_rect()
>> my_rect()
>> my_rect()
>> my_rect()
>> my_rect()
>> ## => spaces between rectangles => why?/how to avoid?
>>
>> __
>> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> 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.

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


[R] What's box() (exactly) doing?

2016-06-23 Thread Marius Hofert
Hi,

I would like to replicate the behavior of box() with rect() (don't ask why).
However, my rect()angles are always too small. I looked a bit into the
internal C_box but
couldn't figure out how to solve the problem. Below is a minimal
working (and a slightly bigger) example.

Cheers,
Marius

## MWE
plot(NA, type = "n", ann = FALSE, axes = FALSE, xlim = 0:1, ylim = 0:1)
rect(xleft = 0, ybottom = 0, xright = 1, ytop = 1, col = "grey80") #
should match box()
box()

## Extended example

## Basic plot
my_rect <- function()
{
plot(NA, type = "n", ann = FALSE, axes = FALSE, xlim = 0:1, ylim = 0:1)
rect(xleft = 0, ybottom = 0, xright = 1, ytop = 1, col = "grey80")
# should match box()
box()
}

## Layout
lay <- matrix(0, nrow = 3, ncol = 3, byrow = TRUE)
lay[1,1] <- 1
lay[2,1] <- 2
lay[2,2] <- 3
lay[2,3] <- 4
lay[3,3] <- 5
layout(lay, heights = c(1, 10, 1), widths = c(10, 1, 10))
layout.show(5) # => no space between rectangles; calls box() to draw the boxes

## Fill layout
par(oma = rep(0, 4), mar = rep(0, 4))
my_rect()
my_rect()
my_rect()
my_rect()
my_rect()
## => spaces between rectangles => why?/how to avoid?

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


[R] How to convert a C vector to an SEXP for using it in R_orderVector()?

2015-03-01 Thread Marius Hofert
Hi,

Inside a C function (foo()), I need to call R's order(). Writing R
Extensions (2014, Section 6.10) gave me the hint to use
R_orderVector() for this task. The third argument of this function
needs an SEXP containing (in my case) the vector x (of which I would
like to determine order()).

My question is: How can I convert the given C vector to an SEXP
acceptable by R_orderVector() [or, if there is an even more efficient
way to call a sort of order() from within C?]?

Here is how my setup roughly looks like: x and y are numeric(n) (but C
vectors obviously). The function should sort x oppositely to y. In R I
can simply do sort(x)[rev(rank(y))] (I wish everything was as easy as
in R...). The problem is: This function is called a million times and
a profiling revealed that 98% of the time is spend there... that's why
I'm looking for a C version (and also to see who much faster the C
version is *and* also to finally go to the dark side and learn a bit
of C again). Here is what my C code looks like so far:

double *foo(double *x, double *y, int n) {
int *indx = malloc(n * sizeof(int)); /* R's order(); will contain
the order (permutation of 0:(n-1)) */
R_orderVector(indx, n, Rf_lang1(*x), /* convert x to SEXP: HOW? */
  TRUE, /* nalast (use same default as order()) */
  TRUE); /* decreasing */
/* => indx == rev(rank(y)) */
R_rsort(x, n); /* R's sort(x) for real x */
double *res = malloc(n * sizeof(double));
for(int i=0; ihttps://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.

Re: [R] Is there a plotmath symbol \mapsto?

2014-12-12 Thread Marius Hofert
Dear Professor Ripley,

Thank you for your reply.
Do you specify \u21A6 via something like this?

plot(1, main=expression(symbol("\u21A6")))

This gives an the 'registered trademark symbol' (circled R) for me
(also cairo-based Linux).

Thanks and cheers,

Marius

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


[R] Is there a plotmath symbol \mapsto?

2014-12-11 Thread Marius Hofert
Hi,

Is there a plotmath symbol like LaTeX's \mapsto?
I need this comparably often, for example if you want to plot a
two-place function in one variable (and thus would like to have
ylab="t \mapsto f(t,s)", for example). If there is such a symbol, I'd
be great to have it as an example on ?plotmath.

Thanks & cheers,

Marius

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


Re: [R] Where to find source of C_pbinom?

2014-08-27 Thread Marius Hofert
Dear Ranjan,

thanks, that was what I was looking for. Somehow my 'grep' must have
missed that.

Cheers,

Marius


On Wed, Aug 27, 2014 at 8:34 AM, Marius Hofert
 wrote:
> Dear Sarah, Dear David,
>
> thanks for helping. I know the FAQ and I know the R News article, but
> I still couldn't figure it out. First, pbinom calls
> .External(C_pbinom,...). Grepping for C_pbinom reveals... nothing
> (except the appearance in .External). Going to ./src/main/names.c
> reveals "{"pbinom", do_math3, 5, 11, 3+2, {PP_FUNCALL, PREC_FN, 0}},",
> so the next step is to grep for do_math3 (which also applies for
> "dbeta", "pbeta",..., "qnbinom_mu"). There is a connection to pbinom
> again in ./src/main/arithmetic.c (SEXP attribute_hidden do_math3):
> Math3_2(args, pbinom) is called. src/library/stats/src/distn.c then
> shows that "Math3_2(args, pbinom)" is called. Since we just already
> grepped for Math3_2, the trip ends here.
>
> So how can one find the source code of pbinom() in this case?
>
> Cheers,
>
> Marius
>
>
> On Wed, Aug 27, 2014 at 7:28 AM, Sarah Goslee  wrote:
>> R FAQ 7.40
>>
>> http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-do-I-access-the-source-code-for-a-function_003f
>>
>> Sarah
>>
>>
>> On Tuesday, August 26, 2014, Marius Hofert 
>> wrote:
>>>
>>> Dear expeRts,
>>>
>>> I would like to find out how R computes pbinom(). A grep in the
>>> source code reveiled src/library/stats/R/distn.R:146:
>>> .External(C_pbinom, q, size, prob, lower.tail, log.p), so
>>> 'C_pbinom' refers to compiled C/C++ code loaded into R. Where can
>>> I find the source code of C_pbinom?
>>>
>>> Cheers,
>>>
>>> Marius
>>>
>>
>>
>> --
>> Sarah Goslee
>> http://www.stringpage.com
>> http://www.sarahgoslee.com
>> http://www.functionaldiversity.org

__
R-help@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.


Re: [R] Where to find source of C_pbinom?

2014-08-27 Thread Marius Hofert
Dear Sarah, Dear David,

thanks for helping. I know the FAQ and I know the R News article, but
I still couldn't figure it out. First, pbinom calls
.External(C_pbinom,...). Grepping for C_pbinom reveals... nothing
(except the appearance in .External). Going to ./src/main/names.c
reveals "{"pbinom", do_math3, 5, 11, 3+2, {PP_FUNCALL, PREC_FN, 0}},",
so the next step is to grep for do_math3 (which also applies for
"dbeta", "pbeta",..., "qnbinom_mu"). There is a connection to pbinom
again in ./src/main/arithmetic.c (SEXP attribute_hidden do_math3):
Math3_2(args, pbinom) is called. src/library/stats/src/distn.c then
shows that "Math3_2(args, pbinom)" is called. Since we just already
grepped for Math3_2, the trip ends here.

So how can one find the source code of pbinom() in this case?

Cheers,

Marius


On Wed, Aug 27, 2014 at 7:28 AM, Sarah Goslee  wrote:
> R FAQ 7.40
>
> http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-do-I-access-the-source-code-for-a-function_003f
>
> Sarah
>
>
> On Tuesday, August 26, 2014, Marius Hofert 
> wrote:
>>
>> Dear expeRts,
>>
>> I would like to find out how R computes pbinom(). A grep in the
>> source code reveiled src/library/stats/R/distn.R:146:
>> .External(C_pbinom, q, size, prob, lower.tail, log.p), so
>> 'C_pbinom' refers to compiled C/C++ code loaded into R. Where can
>> I find the source code of C_pbinom?
>>
>> Cheers,
>>
>> Marius
>>
>
>
> --
> Sarah Goslee
> http://www.stringpage.com
> http://www.sarahgoslee.com
> http://www.functionaldiversity.org

__
R-help@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.


[R] Where to find source of C_pbinom?

2014-08-26 Thread Marius Hofert
Dear expeRts,

I would like to find out how R computes pbinom(). A grep in the
source code reveiled src/library/stats/R/distn.R:146:
.External(C_pbinom, q, size, prob, lower.tail, log.p), so
'C_pbinom' refers to compiled C/C++ code loaded into R. Where can
I find the source code of C_pbinom?

Cheers,

Marius

__
R-help@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.


Re: [R] sort() depends on locale (and platform and build)

2014-06-15 Thread Marius Hofert
Hi,

... so something like this? [in foo.R]

old.coll <- Sys.getlocale("LC_COLLATE")
Sys.setlocale("LC_COLLATE", locale="C")

Sys.setlocale("LC_COLLATE", locale=old.coll)

Cheers,

Marius

__
R-help@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.


Re: [R] sort() depends on locale (and platform and build)

2014-06-15 Thread Marius Hofert
Hi,

Thanks for you help. I use R-devel under Ubuntu 14.04, here is the output of
sessionInfo():

> sessionInfo()
R Under development (unstable) (2014-06-02 r65832)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8   LC_NUMERIC=C
 [3] LC_TIME=en_US.UTF-8LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_US.UTF-8   LC_NAME=C
 [9] LC_ADDRESS=C   LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats graphics  grDevices utils datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_3.2.0 tools_3.2.0


I assume ICU was not found/installed when R was installed as executing the first
couple of lines of the examples section of ?icuSetCollate leads to:

Warning message:
In icuSetCollate(case_first = "upper") : ICU is not supported on this build
[1] "aarhus" "Aarhus" "safe"   "test"   "Zoo"


Since only the (default) locale "C" gives the order I expected, I consider
changing my ~/.Rprofile. But it certainly had a reason why I changed it to
"en_US.UTF-8" at some point... hope that does not break anything else. Is there
any "recommendation" what to use in ~/.Rprofile (the default?)? And is the
'recommended approach' to have ICU installed and change the sorting order via
icuSetCollate if necessary?

I would have not expected any influence of the locale on the sorting order,
that's quite good to know. In fact, the example came up after I tried to sort
students' grades in a class with several students having the same last name
(which I made unique by adding the first names with a '.' separator)... quite a
'delicate' issue...

Cheers,

Marius

__
R-help@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.


[R] sort() depends on locale

2014-06-14 Thread Marius Hofert
Hi,

If I use invisible(Sys.setlocale("LC_COLLATE", "C")) in ~/.Rprofile, then

> sort(c("L.Y", "Lu", "L.Q"))
[1] "L.Q" "L.Y" "Lu"

whereas using invisible(Sys.setlocale("LC_COLLATE", "en_US.UTF-8")) results in

> sort(c("L.Y", "Lu", "L.Q"))
[1] "L.Q" "Lu"  "L.Y"

I know this issue has appeared already
(https://stat.ethz.ch/pipermail/r-help//2012-February/304089.html), I
just don't see a reason for the second output: either '.' comes before
letters, then the result should be
"L.Q" "L.Y" "Lu" or it comes afterwards, then it should be "Lu" "L.Q"
"L.Y" -- the above result thus seems inconsistent to any useful notion
of 'sort' (?)

Cheers,

Marius

__
R-help@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.


Re: [R] (gam) formula: Why different results for terms being factor vs. numeric?

2013-11-02 Thread Marius Hofert
Dear Bert,

Thanks for helping.

Your questions 'answers' why I get the expected behavior if
'group' is a factor. My question was why I don't get the expected
behavior if 'group' is not a factor.

>From a theoretical (non-programming) point of view, there is no
difference in a factor with two levels and a 0-1 (bool/integer)
variable (in my case the 1-2 variable 'group'). gam() interprets
these inputs differently, thus distinguishes these cases (and I
was wondering why; In my opinion, this is a purely R/mgcv related
question and belongs here).

As it turned out, the problem was merely the following: By using
factors and thus specifying a GAM, the intercept was 'hidden' in
the estimated coefficients. When using integers as group
variables, this is a glm and there one needs the intercept. The
examples below provide the details.

With best wishes,

Marius



require(mgcv)
n <- 10
yrs <- 2000+seq_len(n)
loss <- c(seq_len(n)+runif(n), 5+seq_len(n)+runif(n))


## Version 1: gam() with 'group' as factor #

set.seed(271)
dat <- data.frame(year  = rep(yrs, 2),
  group = as.factor(rep(1:2, each=n)), # could also be "A", "B"
  resp  = loss)
fit1 <- glm(resp ~ year + group - 1, data=dat)
plot(yrs, fit1$fitted.values[seq_len(n)], type="l", ylim=range(dat$resp),
 xlab="Year", ylab="Response") # fit group A; mean over all
responses in this group
lines (yrs, fit1$fitted.values[n+seq_len(n)], col="blue") # fit group
B; mean over all responses in this group
points(yrs, dat$resp[seq_len(n)]) # actual response group A
points(yrs, dat$resp[n+seq_len(n)], col="blue") # actual response group B


## Version 2: gam() with 'group' as numeric (=> glm) ###

set.seed(271)
dat <- data.frame(year  = rep(yrs, 2),
  group = rep(1:2, each=n), # could also be 0:1
  resp  = loss)
fit2 <- glm(resp ~ year + group - 1, data=dat) # (*)
plot(yrs, fit2$fitted.values[seq_len(n)], type="l", ylim=range(dat$resp),
 xlab="Year", ylab="Response") # fit group A; mean over all
responses in this group
lines (yrs, fit2$fitted.values[n+seq_len(n)], col="blue") # fit group
B; mean over all responses in this group
points(yrs, dat$resp[seq_len(n)]) # actual response group A
points(yrs, dat$resp[n+seq_len(n)], col="blue") # actual response group B

## Note: without '-1' (intercept) in (*), an unexpected behavior results
## Explanation:
## S. Wiki GAM (without beta_0):
##g(E(Y)) = f_1(x_1) + f_2(x_2)
## where f_i(x_i) may be functions with a specified parametric form
(for example a
## polynomial, or a coefficient depending on the levels of a factor variable)
## => for f_i's being coefficients (numbers) beta_i, this is a GLM:
##g(E(Y)) = beta_1 x_1 + beta_2 x_2 (x_1 = year, x_2 = group)
## Problem: (*) does not specify an intercept and thus the lines are
not picked up correctly
fit2$coefficients


## Version 3: Version 2 with intercept #

set.seed(271)
dat <- data.frame(year  = rep(yrs, 2),
  group = rep(1:2, each=n), # could also be 0:1
  resp  = loss)
fit3 <- glm(resp ~ year + group, data=dat) # now with intercept
plot(yrs, fit3$fitted.values[seq_len(n)], type="l", ylim=range(dat$resp),
 xlab="Year", ylab="Response") # fit group A; mean over all
responses in this group
lines (yrs, fit3$fitted.values[n+seq_len(n)], col="blue") # fit group
B; mean over all responses in this group
points(yrs, dat$resp[seq_len(n)]) # actual response group A
points(yrs, dat$resp[n+seq_len(n)], col="blue") # actual response group B
## => correct/as expected
fit3$coefficients

## Note: in Version 1, the intercept is already included in the group
coefficients:
fit1$coefficients



On Tue, Oct 29, 2013 at 9:31 PM, Bert Gunter  wrote:
> Think about it. How can one define a smooth term with a factor???
>
> Further discussion is probably offtopic. Post on
> stats.stackexchange.com if it still isn't obvious.
>
> Cheers,
> Bert

__
R-help@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.


[R] (gam) formula: Why different results for terms being factor vs. numeric?

2013-10-29 Thread Marius Hofert
Dear expeRts,

If I specify group = as.factor(rep(1:2, each=n)) in the below
definition of dat, I get the expected behavior I am looking for. I
wonder why I
don't get it if group is *not* a factor... My guess was that,
internally, factors are treated as natural numbers (and this indeed
seems to be true if you convert the latter to factors [essentially
meaning changing the levels]), but replacing factors by numeric values
(as below) does not provide the same answer.

Cheers,
Marius


require(mgcv)

n <- 10
yrs <- 2000+seq_len(n)
set.seed(271)
dat <- data.frame(year  = rep(yrs, 2),
  group = rep(1:2, each=n), # *not* a factor
(as.factor() provides the expected behavior)
  resp  = c(seq_len(n)+runif(n), 5+seq_len(n)+runif(n)))
fit3 <- gam(resp ~ year + group - 1, data=dat)
plot(yrs, fit3$fitted.values[seq_len(n)], type="l", ylim=range(dat$resp),
 xlab="Year", ylab="Response") # fit group A; mean over all
responses in this group
lines (yrs, fit3$fitted.values[n+seq_len(n)], col="blue") # fit group
B; mean over all responses in this group
points(yrs, dat$resp[seq_len(n)]) # actual response group A
points(yrs, dat$resp[n+seq_len(n)], col="blue") # actual response group B
## => hmmm... because it is not a factor (?), this does not give an
expected answer,
##but gam() still correctly figures out that there are two groups

__
R-help@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.


[R] double.xmin really the smallest non-zero normalized floating-point number?

2013-09-10 Thread Marius Hofert
Hi,

?.Machine says that 'double.xmin' is 'the smallest non-zero normalized
floating-point number'. On my machine, this is 2.225074e-308. However,
2.225074e-308 / 2 is > 0 and smaller than 2.225074e-308, so
double.xmin is not the smallest such number (?) Am I missing anything?

Cheers,

Marius

__
R-help@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.


Re: [R] double.xmin really the smallest non-zero normalized floating-point number?

2013-09-10 Thread Marius Hofert
On Wed, Sep 11, 2013 at 12:07 AM, William Dunlap  wrote:
> 'normalized' is key.  A normalized double precision floating point
> number has 52 binary digits of precision and .Machine$double.eps/2
> does not.  E.g.,
>
>   > bitsOfPrecision <- function(x)max(which( x != x*(1+2^-(1:60

what a nice function :-)

>   > bitsOfPrecision(4)
>   [1] 52
>   > bitsOfPrecision(.Machine$double.xmin)
>   [1] 52
>   > bitsOfPrecision(.Machine$double.xmin/2)
>   [1] 51
>   > bitsOfPrecision(.Machine$double.xmin/4)
>   [1] 50
>
> Google for 'normalized floating point'.

Okay, thanks a lot.

Do you know whether one can find out the smallest positive number on
the current machine?
Or, actually, I was wondering what the smallest number x is, such that
exp(-x) = 0 in machine arithmetic.
On my machine, x=745 leads to exp(-x) being not quite 0, but x=746
leads to exp(-x)==0 being TRUE. But these are integer x's...

Many thanks and cheers,

Marius


>
> Bill Dunlap
> Spotfire, TIBCO Software
> wdunlap tibco.com
>
>
>> -Original Message-----
>> From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On 
>> Behalf
>> Of Marius Hofert
>> Sent: Tuesday, September 10, 2013 2:50 PM
>> To: R-help
>> Subject: [R] double.xmin really the smallest non-zero normalized 
>> floating-point number?
>>
>> Hi,
>>
>> ?.Machine says that 'double.xmin' is 'the smallest non-zero normalized
>> floating-point number'. On my machine, this is 2.225074e-308. However,
>> 2.225074e-308 / 2 is > 0 and smaller than 2.225074e-308, so
>> double.xmin is not the smallest such number (?) Am I missing anything?
>>
>> Cheers,
>>
>> Marius
>>
>> __
>> R-help@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.

__
R-help@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.


[R] How to construct a 'proper' Q-Q line in log-log space?

2013-06-29 Thread Marius Hofert
Dear expeRts,

I would like to create a Q-Q plot including a Q-Q line for Gamma
distributed data.
The specialty is that it should be in log-log scale. For Q-Q line in
log-log scale,
I discovered the argument 'untf' of abline. As you can see in 2), this
works fine.
But for 3) it does not provide the correct line.

How would one add a Q-Q line to a Q-Q plot in log-log scale?

Cheers,

Marius


th <- 0.5
n <- 250
set.seed(271)
x <- rgamma(n, shape=th)
qF <- function(p) qgamma(p, shape=th)

## 1) Q-Q plot in normal space
plot(qF(ppoints(n)), sort(x))
qqline(y=sort(x), distribution=qF) # fine

## 2) Q-Q plot in log-x space
plot(qF(ppoints(n)), sort(x), log="x")
qqline(y=sort(x), distribution=qF, untf=TRUE) # fine

## 3) Q-Q plot in log-log space
plot(qF(ppoints(n)), sort(x), log="xy")
qqline(y=sort(x), distribution=qF, untf=TRUE) # => wrong!
qqline(y=sort(log(x)), distribution=function(p) log(qF(p)), col="red")
# almost, but not as 'green' below

## 4) Q-Q plot of log values directly
plot(log(qF(ppoints(n))), sort(log(x)))
qqline(y=sort(log(x)), distribution=function(p) log(qF(p)), untf=TRUE,
col="green") # fine

__
R-help@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.


Re: [R] aggregate(), tapply(): Why is the order of the grouping variables not kept?

2013-03-12 Thread Marius Hofert
>
> I'm no expeRt, but suppose that we change the setup slightly:
>
>   xx <- x[sample(nrow(x)), ]
>
> Now what would you like
>
>  aggregate(value ~ group + year, data=xx, FUN=function(z) z[1])
>
> to return?
>
> Personally, I prefer to have R return the same thing regardless
> of how the input dataframe is sorted,

Personally, I prefer to have R not to change my input as much as possible... but
I totally agree with you that there are other instances where it's preferable
that the output does not depend on the input.

> i.e. the result should depend only on the formula. You just have to know that
> the order is to have the first factor vary most rapidly,

... which I still find very confusing/unnatural, but okay.

> then the next, etc.  I think that's documented somewhere, but I don't know
> where.

it's also the default behavior of expand.grid() for example.

Cheers,

Marius

>
>
> Peter Ehlers
>

__
R-help@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.


[R] aggregate(), tapply(): Why is the order of the grouping variables not kept?

2013-03-11 Thread Marius Hofert
Dear expeRts,

The question is rather simple: Why does aggregate (or similarly tapply()) not 
keep the order of the grouping variable(s)?

Here is an example:

x <- data.frame(group = rep(LETTERS[1:2], each=10),
year  = rep(rep(2001:2005, each=2), 2),
value = rep(1:10, each=2))
## => sorted according to group, then year
aggregate(value ~ group + year, data=x, FUN=function(z) z[1])
## => sorted according to year, then group

I rather expected this to be the default:

aggregate(value ~ year + group, data=x, FUN=function(z) z[1])[,c(2,1,3)]
## => same order as input (grouping) variables

Same with tapply:

as.data.frame(as.table(tapply(x$value, list(x$group, x$year), FUN=function(z) 
z[1])))


Cheers,

Marius

__
R-help@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.


Re: [R] How to 'extend' a data.frame based on given variable combinations ?

2013-03-11 Thread Marius Hofert
... okay, I found a solution:

set.seed(1)
x <- data.frame(group = c(rep("A", 4), rep("B", 3)),
year  = c(2001,  2003, 2004, 2005,
 2003, 2004, 2005),
value = rexp(7))

tply <- as.data.frame(as.table(tapply(x$value, list(x$group, x$year), 
FUN=length)),
  nm=colnames(x)) # => 2002 missing
names(tply) <- c("group", "year", "num")
grid <- expand.grid(group = LETTERS[1:2], year=2001:2005) # all variable 
combinations
tply <- merge(grid, tply, by=c("group", "year"), all=TRUE) # merge the two 
data.frames
tply$num[is.na(tply$num)] <- 0
tply


Marius Hofert <> writes:

> Dear expeRts,
>
> I have a data.frame with certain covariate combinations ('group' and 'year')
> and corresponding values:
>
> set.seed(1)
> x <- data.frame(group = c(rep("A", 4), rep("B", 3)),
> year  = c(2001,  2003, 2004, 2005,
>  2003, 2004, 2005),
> value = rexp(7))
>
> My goal is essentially to construct a data.frame which contains all (group, 
> year)
> combinations with corresponding number of values. This can easily be done 
> with tapply():
>
> as.data.frame(as.table(tapply(x$value, list(x$group, x$year), FUN=length))) # 
> => 2002 missing
>
> However, the tricky part is now that I would like to have *all* years in 
> between 2001 and 2005.
> Although tapply() sees the missing year 2001 for group "B" (since group "A" 
> has a value there),
> tapply() does not 'see' the missing year 2002. 
>
> How can such a data.frame be constructed [ideally without using additional R 
> packages]?
>
> Here is a straightforward way (hopelessly inefficient for the application in 
> mind):
>
> num <- cbind(expand.grid(group = LETTERS[1:2], year=2001:2005), num=0)
> covar <- c("group", "year")
> for(i in seq_len(nrow(num)))
> num[i,"num"] <- sum(apply(x[,covar], 1, function(z) all(z == 
> num[i,covar])))
> num
>
> Cheers,
>
> Marius

__
R-help@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.


[R] How to 'extend' a data.frame based on given variable combinations ?

2013-03-11 Thread Marius Hofert
Dear expeRts,

I have a data.frame with certain covariate combinations ('group' and 'year')
and corresponding values:

set.seed(1)
x <- data.frame(group = c(rep("A", 4), rep("B", 3)),
year  = c(2001,  2003, 2004, 2005,
 2003, 2004, 2005),
value = rexp(7))

My goal is essentially to construct a data.frame which contains all (group, 
year)
combinations with corresponding number of values. This can easily be done with 
tapply():

as.data.frame(as.table(tapply(x$value, list(x$group, x$year), FUN=length))) # 
=> 2002 missing

However, the tricky part is now that I would like to have *all* years in 
between 2001 and 2005.
Although tapply() sees the missing year 2001 for group "B" (since group "A" has 
a value there),
tapply() does not 'see' the missing year 2002. 

How can such a data.frame be constructed [ideally without using additional R 
packages]?

Here is a straightforward way (hopelessly inefficient for the application in 
mind):

num <- cbind(expand.grid(group = LETTERS[1:2], year=2001:2005), num=0)
covar <- c("group", "year")
for(i in seq_len(nrow(num)))
num[i,"num"] <- sum(apply(x[,covar], 1, function(z) all(z == num[i,covar])))
num

Cheers,

Marius

__
R-help@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.


Re: [R] How to construct a valid seed for l'Ecuyer's method with given .Random.seed?

2013-01-24 Thread Marius Hofert
Thanks a lot, Duncan, that solved it!

Cheers,

Marius



Duncan Murdoch writes:

> On 13-01-24 2:09 AM, Marius Hofert wrote:
>> Dear Daniel,
>>
>> That's exactly what I also suspected (last post). The question now seems how 
>> to
>> correctly convert .Random.seed from signed to unsigned so that it is 
>> accepted by
>> the rlecuyer package.
>
> The rlecuyer package assumes that seed values are positive internally, because
> it does this conversion in the C code:
>
> seed[i]= (unsigned long) REAL(sexp_seed)[i]
>
> If you send it negative values, the result of this is undefined.
>
> I'd suggest that the .lec.CheckSeed function should check for this and quit if
> it's not true.
>
> When you tried to convert everything to be positive, you used
>
> seed <- .Random.seed[-1] + 2^32
>
> This will put negative values into the right range, but positive values will 
> end
> up too big, and again the results in the C code will overflow.
>
> You should be able to get proper behaviour this way:
>
> seed <- .Random.seed[-1]
> seed <- ifelse(seed < 0, seed + 2^32, seed)
>
> which puts values into the legal range for an unsigned int.  When I do this, I
> don't get an error running
>
> .lec.SetPackageSeed(seed)
>
> You got an error Seed[1] >= 14, which comes from an error in the rlecuyer
> package formatting of the error message.  It is printing a floating point 
> value
> using a %d format, instead of %f.
>
> Duncan Murdoch


pgpl9WD8VQqM2.pgp
Description: PGP signature
__
R-help@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.


Re: [R] How to construct a valid seed for l'Ecuyer's method with given .Random.seed?

2013-01-23 Thread Marius Hofert
Dear Daniel,

That's exactly what I also suspected (last post). The question now seems how to
correctly convert .Random.seed from signed to unsigned so that it is accepted by
the rlecuyer package. 

Cheers,

Marius

__
R-help@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.


Re: [R] How to construct a valid seed for l'Ecuyer's method with given .Random.seed?

2013-01-23 Thread Marius Hofert
Dear Hana,

Thanks for helping.

I am still wondering, why m1 (which should be 2^32-209 [see line 34 in
./src/RngStream.c]) is -767742437 in my case and why the minimal example you
gave was working for you but isn't for me.

Apart from that, ?.Random.seed -> "L'Ecuyer-CMRG" says:

,
| The 6 elements of the seed are internally regarded as 32-bit
| unsigned integers.  Neither the first three nor the last
| three should be all zero, and they are limited to less than
| ‘4294967087’ and ‘429493’ respectively.
`

=> .Random.seed provides a *signed* integer. I tried to convert it to an
unsigned integer:

RNGkind()
set.seed(1)
.Random.seed[-1]
RNGkind("L'Ecuyer-CMRG")
.Random.seed[-1] # => unsigned

seed <- .Random.seed[-1] + 2^32 # => shifting
require(rlecuyer)
.lec.SetPackageSeed(seed)

... but it fails with

,
| Error in .lec.SetPackageSeed(seed) : Seed[1] >= 14, Seed is not set.
`

=> so there seem to be the requirement that the second element of the seed is <
14 (???). 

I might have done the conversion to a signed integer incorrectly, though.

It would be great if the seed was checked *precisely* (not just basic length
checks) in R, maybe in .lec.CheckSeed(). That would rule out further problems
and strange error messages from C, which are harder to debug. 

What are the precise conditions for the seed in 'rlecuyer'? Judging from the
above error, the second element must be < 14. But, additionally,... ?

I hope there is a solution to the problem of "how to convert .Random.seed to get
a valid seed for 'rlecuyer'"... we need that in a package. 

Cheers,

Marius




Hana Sevcikova  writes:

> Marius,
>
> I looked it up in the original L'Ecuyer's paper: The seed must be larger than
> 0. Thus, the function defines the seed variable as unsigned long integer. 
> You're
> passing a negative number, so I think there is some overflow going on.
>
> The internal L'Ecuyer RNG is a modification of the original one (and I'm not
> familiar with it), but they seem to relax that restriction.
>
> Hana


pgphE0xoQvbRe.pgp
Description: PGP signature
__
R-help@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.


Re: [R] How to construct a valid seed for l'Ecuyer's method with given .Random.seed?

2013-01-23 Thread Marius Hofert
Since clusterSetupRNG() calls clusterSetupRNGstream() and this calls 
.lec.SetPackageSeed(), I could further minimalize the problem:

set.seed(1)
RNGkind("L'Ecuyer-CMRG") # => .Random.seed is of length 7 (first number encodes 
the rng kind)
(seed <- .Random.seed[2:7]) # should give a valid seed for l'Ecuyer's RNG
require(rlecuyer) # latest version 0.3-3
.lec.SetPackageSeed(seed)

The last line fails with:

,
| Error in .lec.SetPackageSeed(seed) :
|   Seed[0] >= -767742437, Seed is not set.
`

Looking at .lec.SetPackageSeed, "seed" seems to pass .lec.CheckSeed() [the check
could probably be improved here (but further checking is done in the C code; see
below)]:

,
| > .lec.SetPackageSeed
| function (seed = rep(12345, 6))
| {
| if (!exists(".lec.Random.seed.table", envir = .GlobalEnv))
| .lec.init()
| seed <- .lec.CheckSeed(seed) # => bad check since it's passed
| .Call("r_set_package_seed", as.double(seed), PACKAGE = "rlecuyer") # => 
this fails!
| return(seed)
| }
| 
`

Going into the C code, r_set_package_seed calls RngStream_SetPackageSeed which 
in turn calls CheckSeed(seed). The relevant part of CheckSeed is this:

,
| for (i = 0; i < 3; ++i) {
| if (seed[i] >= m1) {
|   /* HS 01-25-2012 */
|   error("Seed[%1d] >= %d, Seed is not set.\n", i,m1);
|/* original code
|  fprintf (stderr, "\n"
|"ERROR: Seed[%1d] >= m1, Seed is not set.\n"
|"\n\n", i);
|   return (-1);
|*/
|  }
| }
`

Note that seed[0] in this (C-)code corresponds to the first element of my
variable "seed", which is -1535484873. This should definitely be smaller than m1
since m1 is defined as 4294967087.0 on line 34 in ./src/RngStream.c of the 
package 'rlecuyer'.

Why is seed[i] then >= m1??? This is strange. Indeed, as you can see from the
error message above, m1 is taken as -767742437 in my case (why?). Still (and 
even more
confusing), -1535484873 >= -767742437 is FALSE (!) but the if(){} is entered
anyways...


Cheers,

Marius

__
R-help@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.


Re: [R] How to construct a valid seed for l'Ecuyer's method with given .Random.seed?

2013-01-22 Thread Marius Hofert
I updated to the latest CRAN versions of 'rlecuyer', 'Rmpi', and 'snow':

,[ sessionInfo() ]
| ...
| other attached packages:
| [1] rlecuyer_0.3-3 Rmpi_0.6-1 snow_0.3-10   
| ...
`

But I still obtain:

,
| Error in .lec.SetPackageSeed(seed) : 
|   Seed[1] >= -1065242851, Seed is not set.
`

when executing

,
| library(snow)
| RNGkind("L'Ecuyer-CMRG")
| cl <- makeCluster(parallel::detectCores(), type="MPI")
| .t <- snow::clusterSetupRNG(cl, seed=.Random.seed[2:7])
| stopCluster(cl)
`

__
R-help@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.


Re: [R] How to construct a valid seed for l'Ecuyer's method with given .Random.seed?

2013-01-22 Thread Marius Hofert
Dear Hana,

Thanks a lot for helping. That's interesting. What package versions do you use? 

By executing your (even more) minimal example, I get this:

> library(snow)
> RNGkind("L'Ecuyer-CMRG")
> cl <- makeCluster(parallel::detectCores(), type="MPI")
Loading required package: Rmpi
Loading required package: grDevices
Loading required package: grDevices
Loading required package: grDevices
Loading required package: grDevices
4 slaves are spawned successfully. 0 failed.
> .t <- snow::clusterSetupRNG(cl, seed=.Random.seed[2:7])
Loading required package: rlecuyer
Error in .lec.SetPackageSeed(seed) : 
  Seed[0] >= -1002165933, Seed is not set.
> traceback()
4: .Call("r_set_package_seed", as.double(seed), PACKAGE = "rlecuyer")
3: .lec.SetPackageSeed(seed)
2: clusterSetupRNGstream(cl, ...)
1: snow::clusterSetupRNG(cl, seed = .Random.seed[2:7])

Here is the output of sessionInfo()

> sessionInfo()
R version 2.15.2 (2012-10-26)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8   LC_NUMERIC=C  
 [3] LC_TIME=en_US.UTF-8LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=C LC_NAME=C 
 [9] LC_ADDRESS=C   LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C   

attached base packages:
[1] stats graphics  utils datasets  grDevices methods   base 

other attached packages:
[1] rlecuyer_0.3-3 Rmpi_0.5-9 snow_0.3-10   

loaded via a namespace (and not attached):
[1] compiler_2.15.2 parallel_2.15.2 tools_2.15.2   
> 



Hana Sevcikova writes:

> Marius,
>
> It does not fail for me. I'm doing
>
>> library(snow)
>> RNGkind("L'Ecuyer-CMRG")
>> cl <- makeCluster(parallel::detectCores(), type="MPI")
> 4 slaves are spawned successfully. 0 failed.
>> .t <- snow::clusterSetupRNG(cl, seed=.Random.seed[2:7])
>> stopCluster(cl)
>
> Hana
>
>
> On 1/22/13 4:53 PM, Marius Hofert wrote:
>> Dear expeRts,
>>
>> I struggle with the following problem using snow clusters for parallel
>> computing: I would like to specify l'Ecuyer's random number generator. Base R
>> creates a .Random.seed of length 7, the first value indicating the kind fo
>> random number generator. I would thus like to use the components 2 to 7 as 
>> the
>> seed for l'Ecuyer's random number generator.
>>
>> By doing so, I receive (see the minimal example below):
>>
>> ,
>> | > Loading required package: Rmpi
>> | Loading required package: grDevices
>> | Loading required package: grDevices
>> | Loading required package: grDevices
>> | Loading required package: grDevices
>> |4 slaves are spawned successfully. 0 failed.
>> | Loading required package: rlecuyer
>> | Error in .lec.SetPackageSeed(seed) (from #11) :
>> |   Seed[0] >= -930997252, Seed is not set.
>> `
>>
>> What's the problem? How can I construct a valid seed for l'Ecuyer's rng with
>> just the information in .Random.seed?
>>
>> Thanks & Cheers,
>>
>> Marius
>>
>>
>> Here is the minimal example:
>>
>> require(doSNOW)
>> require(foreach)
>>
>> doForeach <- function(n, seed=1, type="MPI")
>> {
>>  ## create cluster object
>>  cl <- snow::makeCluster(parallel::detectCores(), type=type)
>>  on.exit(snow::stopCluster(cl)) ## shut down cluster and terminate 
>> execution environment
>>  registerDoSNOW(cl) ## register the cluster object with foreach
>>
>>  ## seed
>>  if(seed=="L'Ecuyer-CMRG") {
>>  if(!exists(".Random.seed")) stop(".Random.seed does not exist - in 
>> l'Ecuyer setting")
>>  .t <- snow::clusterSetupRNG(cl, seed=.Random.seed[2:7]) # => fails!
>>  }
>>
>>  ## actual work
>>  foreach(i=seq_len(n)) %dopar% {
>>  runif(1)
>>  }
>> }
>>
>> ## "standard" (base) way of specifying l'Ecuyer
>> RNGkind("L'Ecuyer-CMRG") # => .Random.seed is of length 7
>> res <- doForeach(10, seed="L'Ecuyer-CMRG")
>>
>

__
R-help@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.


[R] How to construct a valid seed for l'Ecuyer's method with given .Random.seed?

2013-01-22 Thread Marius Hofert
Dear expeRts,

I struggle with the following problem using snow clusters for parallel 
computing: I would like to specify l'Ecuyer's random number generator. Base R 
creates a .Random.seed of length 7, the first value indicating the kind fo 
random number generator. I would thus like to use the components 2 to 7 as the 
seed for l'Ecuyer's random number generator.

By doing so, I receive (see the minimal example below):

,
| > Loading required package: Rmpi
| Loading required package: grDevices
| Loading required package: grDevices
| Loading required package: grDevices
| Loading required package: grDevices
|   4 slaves are spawned successfully. 0 failed.
| Loading required package: rlecuyer
| Error in .lec.SetPackageSeed(seed) (from #11) :
|   Seed[0] >= -930997252, Seed is not set.
`

What's the problem? How can I construct a valid seed for l'Ecuyer's rng with
just the information in .Random.seed?

Thanks & Cheers,

Marius


Here is the minimal example:

require(doSNOW)
require(foreach)

doForeach <- function(n, seed=1, type="MPI")
{
## create cluster object
cl <- snow::makeCluster(parallel::detectCores(), type=type)
on.exit(snow::stopCluster(cl)) ## shut down cluster and terminate execution 
environment
registerDoSNOW(cl) ## register the cluster object with foreach

## seed
if(seed=="L'Ecuyer-CMRG") {
if(!exists(".Random.seed")) stop(".Random.seed does not exist - in 
l'Ecuyer setting")
.t <- snow::clusterSetupRNG(cl, seed=.Random.seed[2:7]) # => fails!
}

## actual work
foreach(i=seq_len(n)) %dopar% {
runif(1)
}
}

## "standard" (base) way of specifying l'Ecuyer
RNGkind("L'Ecuyer-CMRG") # => .Random.seed is of length 7
res <- doForeach(10, seed="L'Ecuyer-CMRG")

__
R-help@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.


[R] tables package: How to remove column headings and alignment issues

2013-01-18 Thread Marius Hofert
Dear expeRts,

Here is a minimal example with the latest version of 'tables' (questions below):

require(tables)

saveopts <- table_options(toprule="\\toprule", midrule="\\midrule", 
bottomrule="\\bottomrule",
  titlerule="\\cmidrule(lr)", 
rowlabeljustification="r")#, justification="r")

## data.frame
x <- expand.grid(beta=as.factor(c("95", "99", "99.9")),
m=as.factor(c(64, 256)),
p=as.factor(c(8, 64, 512)),
f=as.factor(c("A", "B")),
gamma=as.factor(c(0.25, 0.5)))
x <- cbind(x, value=1:nrow(x))

## tabular
(tab <- tabular(Heading("$p$") * Justify(c) * p *
Heading("$m$") * Justify(c) * m *
Heading("$\\gamma$") * Justify(c) * gamma
~
Heading() * f * Heading() * beta *
Heading() * value * Heading() * identity, data=x))
latex(tab)


Questions:

1) How can the column labels "f" and "beta" be removed? I tried to use 
Heading() to remove the labels, but some of them (actually all except 
"identity") still appear.

2) The above example leads to a tabular with columns aligned like this: 
rrrcc. However, if put in a .tex document, the table entries (1:9) are 
filled with \phantom{0}, so that the numbers do not appear centered (rather 
right-aligned). In contrast, the row labels (given in the first three columns) 
appear centered although they should be right-aligned.

3) Additionally using justification="r" in table_options() provides 
right-justification of the entries, however, they are now all wrapped in 
\multicolumn{1}{c}{...}. Why?

Cheers,

Marius



Here is a .tex wrapper for convenience:

\documentclass{article}

\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[american]{babel}

\usepackage{tabularx}
\usepackage{booktabs}


\begin{document}
  % put code here
\end{document}

__
R-help@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.


[R] How to efficiently compare each row in a matrix with each row in another matrix?

2012-12-08 Thread Marius Hofert
Dear expeRts,

I have two matrices A and B. They have the same number of columns but possibly 
different number of rows. I would like to compare each row of A with each row 
of B and check whether all entries in a row of A are less than or equal to all 
entries in a row of B. Here is a minimal working example:

A <- rbind(matrix(1:4, ncol=2, byrow=TRUE), c(6, 2)) # (3, 2) matrix
B <- matrix(1:10, ncol=2) # (5, 2) matrix
( ind <- apply(B, 1, function(b) apply(A, 1, function(a) all(a <= b))) ) # (3, 
5) = (nrow(A), nrow(B)) matrix

The question is: How can this be implemented more efficiently in R, that is, in 
a faster way?

Thanks & cheers,

Marius

__
R-help@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.


Re: [R] Constant (= wrong) historical quotes via get.hist.quote() from yahoo.finance

2012-11-23 Thread Marius Hofert
Dear Achim,

Thanks a lot for your quick help. Indeed, I did not realize that the "Download 
to
Spreadsheet" gives the wrong result, so it's really a Yahoo! Finance issue (too
bad, an R issue would have been easier to fix :-) ).

Thanks again,

Marius


Achim Zeileis  writes:

> On Fri, 23 Nov 2012, Marius Hofert wrote:
>
>> Dear expeRts,
>>
>> I would like to download a time series of historical data from the ticker 
>> with
>> symbol "ROG.VX". Interestingly, I obtain constant values (138.3 for each day
>> in the chosen period) although the yahoo.finance website tells me that the
>> time series is not at all constant. What's wrong?
>
> Yahoo! Finance.
>
>> require(tseries)
>> hq <- get.hist.quote(instrument="ROG.VX", start="2011-09-09", 
>> end="2012-03-28",
>> quote="Close", provider="yahoo", drop=TRUE)
>> plot(hq) # => constant
>> stopifnot(hq==138.3) # => constant 138.3
>> ## However, under 
>> http://finance.yahoo.com/q/hp?s=ROG.VX&a=08&b=09&c=2011&d=02&e=28&f=2012&g=d&z=66&y=132
>> ## the historical prices are not all equal to 138.3
>
> It's true that that web page displays the prices correctly. However, if you
> click on "Download to Spreadsheet" you also get the constant 138.3 prices. And
> the spreadsheet functionality is what get.hist.quote() and other R interface 
> to
> Yahoo! Finance use.
>
> Hence, you either have to process the HTML table or have to hope that Yahoo!
> Finance fixes the problem. Not sure whether they have functionality to report
> such problems...
>
> Best,
> Z
>


pgpOWEMyVBq8v.pgp
Description: PGP signature
__
R-help@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.


[R] Constant (= wrong) historical quotes via get.hist.quote() from yahoo.finance

2012-11-22 Thread Marius Hofert
Dear expeRts,

I would like to download a time series of historical data from the ticker with 
symbol "ROG.VX". Interestingly, I obtain constant values (138.3 for each day in 
the chosen period) although the yahoo.finance website tells me that the time 
series is not at all constant. What's wrong?

Cheers,

Marius


require(tseries)
hq <- get.hist.quote(instrument="ROG.VX", start="2011-09-09", end="2012-03-28",
 quote="Close", provider="yahoo", drop=TRUE)
plot(hq) # => constant
stopifnot(hq==138.3) # => constant 138.3
## However, under 
http://finance.yahoo.com/q/hp?s=ROG.VX&a=08&b=09&c=2011&d=02&e=28&f=2012&g=d&z=66&y=132
## the historical prices are not all equal to 138.3


pgpxmc2kGwwm9.pgp
Description: PGP signature
__
R-help@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.


[R] \lstdefinelanguage error: undefined control sequence

2012-11-02 Thread Marius Hofert
Dear expeRts,

I'm trying to use the package SweaveListingUtils, but the rather minimal example
below leads to

,
| ./minimal.tex:43: Undefined control sequence.
| l.43 \lstdefinelanguage
|{Rd}[common]{TeX}%
| ?
`

Why?

Cheers,

Marius

\documentclass[article]{jss}

\author{foo \And bar}
\Address{
  foo
  \bigskip
  bar
}
\title{foo bar}
\Plainauthor{foo, bar}
\Plaintitle{foo bar}
\Abstract{foo and bar.}
\Keywords{\R, foo, bar}

\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[american]{babel}
\usepackage{microtype}
\usepackage{Sweave}
\usepackage{fancyvrb}
% do *not* delete the following line! see 
https://stat.ethz.ch/pipermail/r-help/2009-July/204747.html
% this comment persuades Sweave not to insert \usepackage{Sweave}

% Sweave
\fvset{listparameters={\setlength{\topsep}{-2pt}}}
\renewenvironment{Schunk}{\vspace{\topsep}}{\vspace{\topsep}}

% SweaveListingUtils
\SweaveOpts{keep.source=TRUE}
<>=
require(SweaveListingUtils)
SweaveListingPreparations()
@

\begin{document}
<>=
f <- function(n) runif(n, min=-1, max=1)
mean(f(100))
@
\end{document}

<>=
unloadNamespace("SweaveListingUtils")
@

__
R-help@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.


Re: [R] How to nicely display R code with the LaTeX package 'listings'?

2012-11-01 Thread Marius Hofert
Dear Yihui, Dear Frank,

Thanks for helping.

I am aware of Sweave and knitr and this is an incredible development. Still,
this "machinery" is too heavy for my needs. I typically use pure R scripts for
my work (well documented with Roxygen). I can then easily debug and
are not disturbed by additional text already. Also, I can easily run a pure R
script on a computer cluster (not sure about an .Rnw -- okay, one might use a
makefile that first tangles it and then sends the script to the cluster, but 
that
already adds another layer of complexity). Another thing is syncronization
(forward/backward search from .pdf). We recently managed to use Duncan's 
"patchDVI" to
get backward sync to the .Rnw file instead of the .tex file. This was even in a
multi-file document (several .Rnw loaded from a master file) where it is
extremely useful. But that was not so easy to set up (and I am not sure if knitr
does/can incorporate this). The biggest problem,
however, is portability. None of my co-authors (except for Martin) uses such
tools and is therefore able to compile the .Rnw document (they mostly use .tex
and can compile those documents). So for putting in some lines of code in a
paper, this is quite restrictive (that's why I was hoping for a latex-related
solution -- still asking on r-help since I'd expect R users to have encountered
this issue before).

Cheers,

Marius



Yihui Xie  writes:

> Or see https://github.com/yihui/knitr-examples/blob/master/015-listings.Rnw
> for a minimal example.
>
> Regards,
> Yihui
> --
> Yihui Xie 
> Phone: 515-294-2465 Web: http://yihui.name
> Department of Statistics, Iowa State University
> 2215 Snedecor Hall, Ames, IA
>
>
> On Thu, Nov 1, 2012 at 1:23 PM, Frank Harrell  
> wrote:
>> The knitr package makes this relatively easy to do.  See for example
>> http://biostat.mc.vanderbilt.edu/KnitrHowto
>>
>> Frank
>>
>>
>> Marius Hofert-3 wrote
>>> Dear expeRts,
>>>
>>> What's a 'good' (nice-looking, easy-to-read) setup for the LaTeX package
>>> 'listings' to display R code?
>>>
>>> The two versions below are partly inspired by the settings of the package
>>> SweaveListingUtils and
>>> http://r.789695.n4.nabble.com/R-How-to-format-R-code-in-LaTex-documents-td816055.html
>>>
>>> Any suggestions, comments, or improvements are welcome.
>>>
>>> Cheers,
>>>
>>> Marius

__
R-help@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.


[R] How to nicely display R code with the LaTeX package 'listings'?

2012-11-01 Thread Marius Hofert
Dear expeRts,

What's a 'good' (nice-looking, easy-to-read) setup for the LaTeX package
'listings' to display R code?

The two versions below are partly inspired by the settings of the package
SweaveListingUtils and
http://r.789695.n4.nabble.com/R-How-to-format-R-code-in-LaTex-documents-td816055.html

Any suggestions, comments, or improvements are welcome.

Cheers,

Marius

### Version 1 ##

\documentclass{scrartcl}

\usepackage[T1]{fontenc}
\usepackage[american]{babel}

\usepackage{graphicx}
\usepackage{fancyvrb}
\usepackage{listings}

\lstset{% setup listings
language=R,% set programming language
basicstyle=\small,% basic font style
keywordstyle=\bfseries,% keyword style
commentstyle=\ttfamily\itshape,% comment style
numbers=left,% display line numbers on the left side
numberstyle=\scriptsize,% use small line numbers
numbersep=10pt,% space between line numbers and code
tabsize=3,% sizes of tabs
showstringspaces=false,% do not replace spaces in strings by a certain 
character
captionpos=b,% positioning of the caption below
breaklines=true,% automatic line breaking
escapeinside={(*}{*)},% escaping to LaTeX
fancyvrb=true,% verbatim code is typset by listings
extendedchars=false,% prohibit extended chars (chars of codes 128--255)

literate={"}{{\texttt{"}}}1{<-}{{$\leftarrow$}}1{<<-}{{$\twoheadleftarrow$}}1

{~}{{$\sim$}}1{<=}{{$\le$}}1{>=}{{$\ge$}}1{!=}{{$\neq$}}1{^}{{$^\wedge$}}1,% 
item to replace, text, length of chars
alsoletter={.<-},% becomes a letter
alsoother={$},% becomes other
otherkeywords={!=, ~, $, *, \&, \%/\%, \%*\%, \%\%, <-, <<-, /},% other 
keywords
deletekeywords={c}% remove keywords
}

\begin{document}

\noindent Just some text; see Line \ref{foo}.
\begin{lstlisting}[caption={A first example}, label=list:ex]
x <- c(1, 3, 2)
id <- function(x){
x # just a dummy (*\label{foo}*)
}
3 <= 4
3 != 4
!TRUE
y <- "foo"
(pv <- sum(x*x^x))
y ~ x + a
\end{lstlisting}

\end{document}


### Version 2 ##

\documentclass{scrartcl}

\usepackage[T1]{fontenc}
\usepackage[american]{babel}

\usepackage{graphicx}
\usepackage{fancyvrb}
\usepackage{listings}
\usepackage{bm}
\usepackage{xcolor}

\xdefinecolor{gray}{rgb}{0.4,0.4,0.4}
\xdefinecolor{blue}{RGB}{58,95,205}% R's royalblue3; #3A5FCD

\lstset{% setup listings
language=R,% set programming language
basicstyle=\ttfamily\small,% basic font style
keywordstyle=\color{blue},% keyword style
commentstyle=\color{gray},% comment style
numbers=left,% display line numbers on the left side
numberstyle=\scriptsize,% use small line numbers
numbersep=10pt,% space between line numbers and code
tabsize=3,% sizes of tabs
showstringspaces=false,% do not replace spaces in strings by a certain 
character
captionpos=b,% positioning of the caption below
breaklines=true,% automatic line breaking
escapeinside={(*}{*)},% escaping to LaTeX
fancyvrb=true,% verbatim code is typset by listings
extendedchars=false,% prohibit extended chars (chars of codes 128--255)

literate={"}{{\texttt{"}}}1{<-}{{$\bm\leftarrow$}}1{<<-}{{$\bm\twoheadleftarrow$}}1

{~}{{$\bm\sim$}}1{<=}{{$\bm\le$}}1{>=}{{$\bm\ge$}}1{!=}{{$\bm\neq$}}1{^}{{$^{\bm\wedge}$}}1,%
 item to replace, text, length of chars
alsoletter={.<-},% becomes a letter
alsoother={$},% becomes other
otherkeywords={!=, ~, $, \&, \%/\%, \%*\%, \%\%, <-, <<-, /},% other 
keywords
deletekeywords={c}% remove keywords
}

\begin{document}

\noindent Just some text; see Line \ref{foo}.
\begin{lstlisting}[caption={A first example}, label=list:ex]
x <- c(1, 3, 2)
id <- function(x){
x # just a dummy (*\label{foo}*)
}
3 <= 4
3 != 4
!TRUE
y <- "foo"
(pv <- sum(x*x^x))
y ~ x + a
\end{lstlisting}

\end{document}

__
R-help@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.


Re: [R] grid(Base): How to avoid "Figure region too small and/or viewport too large" by specifying 'relative' units?

2012-10-22 Thread Marius Hofert
Dear Paul,

Thank you very much for helping, works perfectly fine. 

I now see the scaling when looking at grid.show.layout(), but I would have never
come up with looking there in the first place :-)

Cheers,

Marius


Paul Murrell  writes:

> Hi
>
> Apologies for the slow response.
>
> This part of the problem is I think just a bit of a misunderstanding. The
> diagram drawn by grid.show.viewport() is drawn within a *subset* of the 
> current
> page (or viewport), to allow room for labelling, which is why your subsequent
> "real" viewports do not align with the diagram.
> If you change your grid.show.layout() call to the following (which "removes" 
> the
> normal margin used by grid.show.layout()) ...
>
> grid.show.layout(gl, vp=viewport(width=1.25, height=1.25))
>
> ... then you should find your viewports line up with the diagram properly.
>
> Paul
>
> On 20/10/12 19:10, Marius Hofert wrote:
>> In the meanwhile, I found a more minimal example which shows the problem 
>> (just
>> change 'inch' to TRUE to see the difference):
>>
>>
>> require(grid)
>>
>> inch <- FALSE # TRUE
>>
>> d <- if(inch) 5 else 1
>> pspc <- d*c(0.3, 0.3) # width, height of panels
>> spc <- d*c(0.05, 0.05) # width, height of space
>> axlabspc <- d*c(0.1, 0.1) # width y label, height x label
>> labspc <- d*c(0.05, 0.05) # width label boxes, height label boxes
>>
>> par. <- par(no.readonly=TRUE)
>> gl <- grid.layout(5, 5, default.units=if(inch) "inches" else "npc",
>>widths=c(axlabspc[1], pspc[1], spc[1], pspc[1], 
>> labspc[1]),
>>heights=c(labspc[2], pspc[2], spc[2], pspc[2], 
>> axlabspc[2]))
>> grid.show.layout(gl)
>> pushViewport(viewport(layout=gl))
>> for(i in 1:2) {
>>  for(j in 1:2) {
>>  pushViewport(viewport(layout.pos.row=2*i, layout.pos.col=2*j, 
>> name="foo"))
>>  grid.rect()
>>  upViewport()
>>  }
>> }
>> par(par.)
>>
>> __
>> R-help@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.
>>

__
R-help@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.


Re: [R] quantile regression using copulas

2012-10-21 Thread Marius Hofert
Please note:

1) your example is not working in the way you provided it (see
http://www.minimalbeispiel.de/mini-en.html)
2) you receive a warning, not an error
3) I'd try and debug qua.regressCOP2 to see why the warning appears
4) in case 3) does not help, contact the maintainer of copBasic (William
H. Asquith )

Having said the above, the warning message "... could not uniroot..." is indeed
weak. I guess (without looking at the code) that derCOPinv2 computes some kind
of inverse of the derivative of a copula with respect to one argument. This
often appears since it is the quantile function of a conditional copula. If the
inversion is done via uniroot, it might not be numerically 100% stable and you
probably ran into a case where something strange happened there (not too strange
though, since it's just a warning). But if you debug it (use
debug(qua.regressCOP2) and call your example again) and find the flaw, you can
give the maintainer feedback how the function can be improved so that you won't
run into this problem again in the future. 

Cheers,

Marius

__
R-help@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.


Re: [R] grid(Base): How to avoid "Figure region too small and/or viewport too large" by specifying 'relative' units?

2012-10-19 Thread Marius Hofert
In the meanwhile, I found a more minimal example which shows the problem (just
change 'inch' to TRUE to see the difference):


require(grid)

inch <- FALSE # TRUE

d <- if(inch) 5 else 1
pspc <- d*c(0.3, 0.3) # width, height of panels
spc <- d*c(0.05, 0.05) # width, height of space
axlabspc <- d*c(0.1, 0.1) # width y label, height x label
labspc <- d*c(0.05, 0.05) # width label boxes, height label boxes

par. <- par(no.readonly=TRUE)
gl <- grid.layout(5, 5, default.units=if(inch) "inches" else "npc",
  widths=c(axlabspc[1], pspc[1], spc[1], pspc[1], labspc[1]),
  heights=c(labspc[2], pspc[2], spc[2], pspc[2], axlabspc[2]))
grid.show.layout(gl)
pushViewport(viewport(layout=gl))
for(i in 1:2) {
for(j in 1:2) {
pushViewport(viewport(layout.pos.row=2*i, layout.pos.col=2*j, 
name="foo"))
grid.rect()
upViewport()
}
}
par(par.)

__
R-help@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.


[R] grid(Base): How to avoid "Figure region too small and/or viewport too large" by specifying 'relative' units?

2012-10-19 Thread Marius Hofert
Dear grid-expeRts,

The goal: 
I would like to construct a plot (matrix) with grid and gridBase,
which consists of four "sub-plots". The sub-plots should have a square plotting
region as one would force with par(pty="s") in base graphics.

The problem: 
I don't get a square plotting region, not even by specifying
pty="s" in par(). Indeed, if you display the grid layout by commenting in
"grid.show.layout(gl)" below, you'll see that the grid layout is fine, but the
plot does not seem to respect the layout measurements.

The initial quick-and-dirty hack: 
Use absolute measurements, i.e., specify all
units in inches. This worked perfectly fine for me initially. However, when the
device width and height are not set accordingly (and one can never know what
others specify here -- indeed the problem arose this way), this produces errors
of type "Error in gridPLT() : Figure region too small and/or viewport too
large".

I also found this issue in this post
(https://stat.ethz.ch/pipermail/r-help/2008-December/181993.html), but I am
wondering what's the correct approach towards this problem / how can one specify
"relative" units but guarantee that the grid layout is respected when plotting
is done? [We use this plot in a quite complicated setup and the quick solution
to specify inches and a large enough width/height for the device fails.]


Cheers,

Marius


require(grid)
require(gridBase)

## setup
strg <- LETTERS[1:2] # row variables
t <- c(0.2, 0.8) # column variables

## plot variables (spaces)
pspc <- c(3,3)
spc <- c(0.3, 0.3)
axlabspc <- c(1.2, 0.75)
labspc <- c(0.3, 0.3)

## save plot settings
par. <- par(no.readonly=TRUE)

## set up the grid layout
nx <- 2 # number of sub-plots per column
nx. <- 5 # number of grid rectangles per column
ny <- 2 # number of sub-plots per row
ny. <- 5 # number of grid rectangles per row
plot.new() # start (empty) new page with 'graphics'
gl <- grid.layout(nx., ny., # "2 x 2" grid together with spaces => 5 x 5 grid
  widths=c(axlabspc[1], rep(c(pspc[1], spc[1]), nx-1), pspc[1], 
labspc[1]),
  heights=c(labspc[2], rep(c(pspc[2], spc[2]), ny-1), pspc[2], 
axlabspc[2]))
## grid.show.layout(gl) # display the layout; use this to see that the 
sub-plots do not match the layout specification
pushViewport(viewport(layout=gl)) # use this layout in a viewport

## generate dummy data to plot in the four sub-plots
n <- 10
x <- array(NA, dim=c(nx, ny, n))
for(i in 1:2) for(j in 1:2) x[i,j,] <- rep(i,n)+rep(j,n)+runif(n)

## go through the "panels"
set.seed(1)
for(i in 1:nx) { # rows
i. <- 2*i # column index in layout (for jumping over gaps)
yran <- range(x[i,,]) # for forcing the same y-axis within a row
for(j in 1:ny) { # columns
j. <- 2*j # row index in layout (for jumping over gaps)
pushViewport(viewport(layout.pos.row=i., layout.pos.col=j.))

## plot
par(plt=gridPLT()) # start a 'graphics' plot
par(new=TRUE) # always do this before each new 'graphics' plot
plot(range(1:n), yran, type="n", ann=FALSE, axes=FALSE) # set up 
coordinate axes
points(1:n, x[i,j,], type="b") # actual plot
grid.rect()

## axes
if(i==nx) axis(1) # x axis
if(j==1) axis(2) # y axes
upViewport()

## column labels
if(i==1){
pushViewport(viewport(layout.pos.row=1, layout.pos.col=j.))
grid.rect()
grid.text(t[j], x=0.5, y=0.5)
upViewport()
}

## row labels
if(j==2){
pushViewport(viewport(layout.pos.row=i., layout.pos.col=nx.))
grid.rect()
grid.text(strg[i], x=0.5, y=0.5, rot=-90)
upViewport()
}
}
}

## x axis label
pushViewport(viewport(layout.pos.row=ny., layout.pos.col=2:(ny.-1)))
grid.text(expression(gamma), y=unit(0.5, "null"))
upViewport()

## y axis label
pushViewport(viewport(layout.pos.row=2:(nx.-1), layout.pos.col=1))
grid.text(expression(f[gamma]), rot=90, x=unit(0.5, "null"))
upViewport()

## restore plot settings
par(par.)

__
R-help@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.


Re: [R] Background color in a grid plot seems to interfere with plot()

2012-09-26 Thread Marius Hofert
Dear Paul,

Many thanks, that solved it.

Cheers,

Marius

Paul Murrell  writes:

> Hi
>
> On 25/09/2012 6:10 p.m., Marius Hofert wrote:
>> Dear Paul,
>>
>> Thanks. Redrawing the points solves it for the minimal example, but
>> what happens if you have plot(.., type="b") like below?
>
> You can use points(..., type="b")
>
> Paul
>
>> Actually, originally I wanted to use just grid (without mixing it
>> with base graphics), but I couldn't find an equivalent for plot(..,
>> type="b"). Also, later on, I would like to use eaxis() to draw nice
>> y-axes in log-scale. I guess that's easier with gridBase then.
>>
>> Cheers,
>>
>> Marius
>>
>>
>>
>> require(grid) require(gridBase)
>>
>> pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)
>>
>> ## set up the grid layout plot.new() # start (empty) new page with
>> 'graphics' gl<- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8, 8, 0.8),
>> "cm"), heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
>> pushViewport(viewport(layout=gl))
>>
>> ## plot data par.<- par(no.readonly=TRUE) # save plot settings for(i
>> in 1:2) { # rows i.<- if(i>  1) i+2 else i+1 # jumping over gaps
>> for(j in 1:2) { # columns j.<- if(j>  1) j+2 else j+1 # jumping over
>> gaps pushViewport(viewport(layout.pos.row=i., layout.pos.col=j.))
>> grid.rect(gp=gpar(col=NA, fill="gray90")) # background
>> par(plt=gridPLT()) ## plot par(new=TRUE) # always do this before each
>> new 'graphics' plot plot(runif(5), runif(5), type="b", log="y",
>> xlab="", ylab="", frame.plot=FALSE, xaxt="n", yaxt="n")
>> grid(col="white", lty="solid", lwd=1.6, equilogs=FALSE) # background
>> grid upViewport() } } par(par.) dev.off()
>>
>>
>> Paul Murrell  writes:
>>
>>> Hi
>>>
>>> On 25/09/12 11:50, Marius Hofert wrote:
>>>> Dear Paul,
>>>>
>>>> Thanks for helping. Is there a way to call grid() first? The
>>>> problem seems to be that everything drawn before grid() is
>>>> overplotted.
>>>
>>> No, but you can redraw the points ...
>>>
>>> require(grid) require(gridBase)
>>>
>>> pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)
>>>
>>> ## set up the grid layout plot.new() # start (empty) new page with
>>> 'graphics' gl<- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8, 8,
>>> 0.8), "cm"), heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
>>> pushViewport(viewport(layout=gl))
>>>
>>> ## plot data par.<- par(no.readonly=TRUE) # save plot settings
>>> for(i in 1:2) { # rows i.<- if(i>  1) i+2 else i+1 # jumping over
>>> gaps for(j in 1:2) { # columns j.<- if(j>  1) j+2 else j+1 #
>>> jumping over gaps pushViewport(viewport(layout.pos.row=i.,
>>> layout.pos.col=j.)) grid.rect(gp=gpar(col=NA, fill="gray90")) #
>>> background par(plt=gridPLT()) ## plot par(new=TRUE) # always do
>>> this before each new 'graphics' plot plot(1:5, if(i==1&&  j==2)
>>> c(1, 1, 2, 3, 1) else 1:5, log="y", xlab="", ylab="",
>>> frame.plot=FALSE, xaxt="n", yaxt="n") # background grid
>>> grid(col="white", lty="solid", lwd=1.6, equilogs=FALSE) points(1:5,
>>> if(i==1&&  j==2) c(1, 1, 2, 3, 1) else 1:5) upViewport() } }
>>> par(par.) dev.off()
>>>
>>> Paul
>>>
>>>> Cheers,
>>>>
>>>> Marius
>>>>
>>>>
>>>>
>>>> require(grid) require(gridBase)
>>>>
>>>> pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)
>>>>
>>>> ## set up the grid layout plot.new() # start (empty) new page
>>>> with 'graphics' gl<- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8,
>>>> 8, 0.8), "cm"), heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
>>>> pushViewport(viewport(layout=gl))
>>>>
>>>> ## plot data par.<- par(no.readonly=TRUE) # save plot settings
>>>> for(i in 1:2) { # rows i.<- if(i>  1) i+2 else i+1 # jumping over
>>>> gaps for(j in 1:2) { # columns j.<- if(j>  1) j+2 else j+1 #
>>>> jumping over gaps pushViewport(viewport(layout.pos.row=i.,
>>>> layout.pos.col=j.)) gr

Re: [R] Background color in a grid plot seems to interfere with plot()

2012-09-24 Thread Marius Hofert
Dear Paul,

Thanks. Redrawing the points solves it for the minimal example, but what happens
if you have plot(.., type="b") like below? 

Actually, originally I wanted to use just grid (without mixing it with base
graphics), but I couldn't find an equivalent for plot(.., type="b"). Also, later
on, I would like to use eaxis() to draw nice y-axes in log-scale. I guess that's
easier with gridBase then. 

Cheers,

Marius



require(grid)
require(gridBase)

pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)

## set up the grid layout
plot.new() # start (empty) new page with 'graphics'
gl <- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8, 8, 0.8), "cm"),
  heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
pushViewport(viewport(layout=gl))

## plot data
par. <- par(no.readonly=TRUE) # save plot settings
for(i in 1:2) { # rows
 i. <- if(i > 1) i+2 else i+1 # jumping over gaps
 for(j in 1:2) { # columns
 j. <- if(j > 1) j+2 else j+1 # jumping over gaps
 pushViewport(viewport(layout.pos.row=i., layout.pos.col=j.))
 grid.rect(gp=gpar(col=NA, fill="gray90")) # background
 par(plt=gridPLT())
 ## plot
 par(new=TRUE) # always do this before each new 'graphics' plot
 plot(runif(5), runif(5), type="b",
  log="y", xlab="", ylab="", frame.plot=FALSE, xaxt="n", yaxt="n")
 grid(col="white", lty="solid", lwd=1.6, equilogs=FALSE) # background 
grid
 upViewport()
 }
}
par(par.)
dev.off()


Paul Murrell  writes:

> Hi
>
> On 25/09/12 11:50, Marius Hofert wrote:
>> Dear Paul,
>>
>> Thanks for helping. Is there a way to call grid() first? The problem seems 
>> to be
>> that everything drawn before grid() is overplotted.
>
> No, but you can redraw the points ...
>
> require(grid)
> require(gridBase)
>
> pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)
>
> ## set up the grid layout
> plot.new() # start (empty) new page with 'graphics'
> gl <- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8, 8, 0.8), "cm"),
> heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
> pushViewport(viewport(layout=gl))
>
> ## plot data
> par. <- par(no.readonly=TRUE) # save plot settings
> for(i in 1:2) { # rows
>  i. <- if(i > 1) i+2 else i+1 # jumping over gaps
>  for(j in 1:2) { # columns
>  j. <- if(j > 1) j+2 else j+1 # jumping over gaps
>  pushViewport(viewport(layout.pos.row=i., layout.pos.col=j.))
>  grid.rect(gp=gpar(col=NA, fill="gray90")) # background
>  par(plt=gridPLT())
>  ## plot
>  par(new=TRUE) # always do this before each new 'graphics' plot
>  plot(1:5, if(i==1 && j==2) c(1, 1, 2, 3, 1) else 1:5,
>   log="y", xlab="", ylab="", frame.plot=FALSE, xaxt="n",
>   yaxt="n")
>  # background grid
>  grid(col="white", lty="solid", lwd=1.6, equilogs=FALSE)
>  points(1:5, if(i==1 && j==2) c(1, 1, 2, 3, 1) else 1:5)
>  upViewport()
>  }
> }
> par(par.)
> dev.off()
>
> Paul
>
>> Cheers,
>>
>> Marius
>>
>>
>>
>> require(grid)
>> require(gridBase)
>>
>> pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)
>>
>> ## set up the grid layout
>> plot.new() # start (empty) new page with 'graphics'
>> gl <- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8, 8, 0.8), "cm"),
>>heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
>> pushViewport(viewport(layout=gl))
>>
>> ## plot data
>> par. <- par(no.readonly=TRUE) # save plot settings
>> for(i in 1:2) { # rows
>>   i. <- if(i > 1) i+2 else i+1 # jumping over gaps
>>   for(j in 1:2) { # columns
>>   j. <- if(j > 1) j+2 else j+1 # jumping over gaps
>>   pushViewport(viewport(layout.pos.row=i., layout.pos.col=j.))
>>   grid.rect(gp=gpar(col=NA, fill="gray90")) # background
>>   par(plt=gridPLT())
>>   ## plot
>>   par(new=TRUE) # always do this before each new 'graphics' plot
>>   plot(1:5, if(i==1 && j==2) c(1, 1, 2, 3, 1) else 1:5,
>>log="y", xlab="", ylab="", frame.plot=FALSE, xaxt="n", 
>> yaxt="n")
>>   grid(col="white", lty="solid", lwd=1.6,

Re: [R] Background color in a grid plot seems to interfere with plot()

2012-09-24 Thread Marius Hofert
Dear Paul,

Thanks for helping. Is there a way to call grid() first? The problem seems to be
that everything drawn before grid() is overplotted. 

Cheers,

Marius



require(grid)
require(gridBase)

pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)

## set up the grid layout
plot.new() # start (empty) new page with 'graphics'
gl <- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8, 8, 0.8), "cm"),
  heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
pushViewport(viewport(layout=gl))

## plot data
par. <- par(no.readonly=TRUE) # save plot settings
for(i in 1:2) { # rows
 i. <- if(i > 1) i+2 else i+1 # jumping over gaps
 for(j in 1:2) { # columns
 j. <- if(j > 1) j+2 else j+1 # jumping over gaps
 pushViewport(viewport(layout.pos.row=i., layout.pos.col=j.))
 grid.rect(gp=gpar(col=NA, fill="gray90")) # background
 par(plt=gridPLT())
 ## plot
 par(new=TRUE) # always do this before each new 'graphics' plot
 plot(1:5, if(i==1 && j==2) c(1, 1, 2, 3, 1) else 1:5,
  log="y", xlab="", ylab="", frame.plot=FALSE, xaxt="n", yaxt="n")
 grid(col="white", lty="solid", lwd=1.6, equilogs=FALSE) # background 
grid
 upViewport()
 }
}
par(par.)
dev.off()


Paul Murrell  writes:

> Hi
>
> On 24/09/12 18:06, Marius Hofert wrote:
>> Dear Paul,
>>
>> Thank you for helping. This works great.
>>
>> I then tried to put in a grid (via grid()). Why does that fail?
>
> Because grid() is used to add lines to an existing plot;  just put the grid()
> call AFTER the plot() call and it should work ok.
>
> Paul
>
>> Cheers,
>>
>> Marius
>>
>>
>> require(grid)
>> require(gridBase)
>>
>> pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)
>>
>> ## set up the grid layout
>> plot.new() # start (empty) new page with 'graphics'
>> gl <- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8, 8, 0.8), "cm"),
>>heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
>> pushViewport(viewport(layout=gl))
>>
>> ## plot data
>> par. <- par(no.readonly=TRUE) # save plot settings
>> for(i in 1:2) { # rows
>>  i. <- if(i > 1) i+2 else i+1 # jumping over gaps
>>  for(j in 1:2) { # columns
>>  j. <- if(j > 1) j+2 else j+1 # jumping over gaps
>>  pushViewport(viewport(layout.pos.row=i., layout.pos.col=j.))
>>  grid.rect(gp=gpar(fill="gray90")) # background
>>  par(plt=gridPLT())
>>  ## plot
>>  par(new=TRUE) # always do this before each new 'graphics' plot
>>  grid(col=1)
>>  plot(1:10, 1:10, log="y", xlab="", ylab="",
>>   xaxt=if(i==2) "s" else "n", yaxt=if(j==1) "s" else "n")
>>  upViewport()
>>  }
>> }
>> par(par.)
>> dev.off()
>>
>>
>>
>> Paul Murrell  writes:
>>
>>> Hi
>>>
>>> On 24/09/12 09:36, Marius Hofert wrote:
>>>> Hi,
>>>>
>>>> Why does the upper left panel (in the plot below) not have a gray 
>>>> background?
>>>
>>> That is a symptom of the conflict that occurs when the 'graphics' package 
>>> and
>>> the 'grid' package both try to initialise a new page.
>>> A good rule of thumb is to start a new page with 'graphics' first and THEN 
>>> add
>>> grid' stuff ('grid' is better at sharing), so a minor adjustment to your 
>>> code
>>> would be (#PAUL marks the changes) ...
>>>
>>>
>>> pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)
>>> #PAUL
>>> # Start (empty) new page with 'graphics'
>>> plot.new()
>>> ## set up the grid layout
>>> gl <- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8, 8, 0.8), "cm"),
>>>   heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
>>> pushViewport(viewport(layout=gl))
>>> ## plot data
>>> par. <- par(no.readonly=TRUE) # save plot settings
>>> for(i in 1:2) { # rows
>>>  i. <- if(i > 1) i+2 else i+1 # jumping over gaps
>>>  for(j in 1:2) { # columns
>>>  j. <- if(j > 1) j+2 else j+1 # jumping over gaps
>>>  pushViewport(viewport(layout.pos.row=i., layout.pos.col=j.))
>>>  grid.rect(gp=

Re: [R] Background color in a grid plot seems to interfere with plot()

2012-09-23 Thread Marius Hofert
Dear Jeff,

Thanks for helping.

I thought that gridBase would take care of using simple 'graphics' and grid
plots (?)

I tried grid.grill, but it's not so trivial to set it up such that the grid is
drawn at the axis ticks.

Cheers,

Marius


Jeff Newmiller  writes:

> Same reason.
>
> grid() is part of base graphics, which are incompatible with grid graphics.
>
> Perhaps you want grid.grill(), which you could find out about in the grid
> graphics vignette mentioned earlier.
> ---
> Jeff NewmillerThe .   .  Go Live...
> DCN:Basics: ##.#.   ##.#.  Live Go...
>   Live:   OO#.. Dead: OO#..  Playing
> Research Engineer (Solar/BatteriesO.O#.   #.O#.  with
> /Software/Embedded Controllers)   .OO#.   .OO#.  rocks...1k
> ---
> Sent from my phone. Please excuse my brevity.
>
> Marius Hofert  wrote:
>
>>Dear Paul,
>>
>>Thank you for helping. This works great.
>>
>>I then tried to put in a grid (via grid()). Why does that fail?
>>
>>Cheers,
>>
>>Marius
>>
>>
>>require(grid)
>>require(gridBase)
>>
>>pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)
>>
>>## set up the grid layout
>>plot.new() # start (empty) new page with 'graphics'
>>gl <- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8, 8, 0.8), "cm"),
>>heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
>>pushViewport(viewport(layout=gl))
>>
>>## plot data
>>par. <- par(no.readonly=TRUE) # save plot settings
>>for(i in 1:2) { # rows
>>i. <- if(i > 1) i+2 else i+1 # jumping over gaps
>>for(j in 1:2) { # columns
>>j. <- if(j > 1) j+2 else j+1 # jumping over gaps
>>pushViewport(viewport(layout.pos.row=i., layout.pos.col=j.))
>>grid.rect(gp=gpar(fill="gray90")) # background
>>par(plt=gridPLT())
>>## plot
>>par(new=TRUE) # always do this before each new 'graphics' plot
>>grid(col=1)
>>plot(1:10, 1:10, log="y", xlab="", ylab="",
>> xaxt=if(i==2) "s" else "n", yaxt=if(j==1) "s" else "n")
>>upViewport()
>>}
>>}
>>par(par.)
>>dev.off()
>>
>>
>>
>>Paul Murrell  writes:
>>
>>> Hi
>>>
>>> On 24/09/12 09:36, Marius Hofert wrote:
>>>> Hi,
>>>>
>>>> Why does the upper left panel (in the plot below) not have a gray
>>background?
>>>
>>> That is a symptom of the conflict that occurs when the 'graphics'
>>package and
>>> the 'grid' package both try to initialise a new page.
>>> A good rule of thumb is to start a new page with 'graphics' first and
>>THEN add
>>> grid' stuff ('grid' is better at sharing), so a minor adjustment to
>>your code
>>> would be (#PAUL marks the changes) ...
>>>
>>>
>>> pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)
>>> #PAUL
>>> # Start (empty) new page with 'graphics'
>>> plot.new()
>>> ## set up the grid layout
>>> gl <- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8, 8, 0.8), "cm"),
>>>   heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
>>> pushViewport(viewport(layout=gl))
>>> ## plot data
>>> par. <- par(no.readonly=TRUE) # save plot settings
>>> for(i in 1:2) { # rows
>>> i. <- if(i > 1) i+2 else i+1 # jumping over gaps
>>> for(j in 1:2) { # columns
>>> j. <- if(j > 1) j+2 else j+1 # jumping over gaps
>>> pushViewport(viewport(layout.pos.row=i., layout.pos.col=j.))
>>> grid.rect(gp=gpar(fill="gray90")) # background
>>> par(plt=gridPLT())
>>> ## plot
>>> #PAUL
>>> # ALWAYS do this before each new 'graphics' plot
>>> par(new=TRUE)
>>> plot(1:10, 1:10, log="y", xlab="", ylab="",
>>>  xaxt=if(i==2) "s" else "n", yaxt=if(j==1) "s" else "n")
>>> upViewport()
>>> }
>>> }
>>> par(par.)
>>> dev.

Re: [R] Background color in a grid plot seems to interfere with plot()

2012-09-23 Thread Marius Hofert
Dear Paul,

Thank you for helping. This works great. 

I then tried to put in a grid (via grid()). Why does that fail? 

Cheers,

Marius


require(grid)
require(gridBase)

pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)

## set up the grid layout
plot.new() # start (empty) new page with 'graphics'
gl <- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8, 8, 0.8), "cm"),
  heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
pushViewport(viewport(layout=gl))

## plot data
par. <- par(no.readonly=TRUE) # save plot settings
for(i in 1:2) { # rows
i. <- if(i > 1) i+2 else i+1 # jumping over gaps
for(j in 1:2) { # columns
j. <- if(j > 1) j+2 else j+1 # jumping over gaps
pushViewport(viewport(layout.pos.row=i., layout.pos.col=j.))
grid.rect(gp=gpar(fill="gray90")) # background
par(plt=gridPLT())
## plot
par(new=TRUE) # always do this before each new 'graphics' plot
grid(col=1)
plot(1:10, 1:10, log="y", xlab="", ylab="",
 xaxt=if(i==2) "s" else "n", yaxt=if(j==1) "s" else "n")
upViewport()
}
}
par(par.)
dev.off()



Paul Murrell  writes:

> Hi
>
> On 24/09/12 09:36, Marius Hofert wrote:
>> Hi,
>>
>> Why does the upper left panel (in the plot below) not have a gray background?
>
> That is a symptom of the conflict that occurs when the 'graphics' package and
> the 'grid' package both try to initialise a new page.
> A good rule of thumb is to start a new page with 'graphics' first and THEN add
> grid' stuff ('grid' is better at sharing), so a minor adjustment to your code
> would be (#PAUL marks the changes) ...
>
>
> pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)
> #PAUL
> # Start (empty) new page with 'graphics'
> plot.new()
> ## set up the grid layout
> gl <- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8, 8, 0.8), "cm"),
> heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
> pushViewport(viewport(layout=gl))
> ## plot data
> par. <- par(no.readonly=TRUE) # save plot settings
> for(i in 1:2) { # rows
> i. <- if(i > 1) i+2 else i+1 # jumping over gaps
> for(j in 1:2) { # columns
> j. <- if(j > 1) j+2 else j+1 # jumping over gaps
> pushViewport(viewport(layout.pos.row=i., layout.pos.col=j.))
> grid.rect(gp=gpar(fill="gray90")) # background
> par(plt=gridPLT())
> ## plot
> #PAUL
> # ALWAYS do this before each new 'graphics' plot
> par(new=TRUE)
> plot(1:10, 1:10, log="y", xlab="", ylab="",
>  xaxt=if(i==2) "s" else "n", yaxt=if(j==1) "s" else "n")
> upViewport()
> }
> }
> par(par.)
> dev.off()
>
>
> Hope that helps.
>
> Paul
>
>> Cheers,
>>
>> Marius
>>
>>
>> require(grid)
>> require(gridBase)
>>
>> pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)
>>
>> ## set up the grid layout
>> gl <- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8, 8, 0.8), "cm"),
>>heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
>> if(FALSE) grid.show.layout(gl)
>> pushViewport(viewport(layout=gl))
>>
>> ## plot data
>> par. <- par(no.readonly=TRUE) # save plot settings
>> for(i in 1:2) { # rows
>>  i. <- if(i > 1) i+2 else i+1 # jumping over gaps
>>  for(j in 1:2) { # columns
>>  j. <- if(j > 1) j+2 else j+1 # jumping over gaps
>>  pushViewport(viewport(layout.pos.row=i., layout.pos.col=j.))
>>  grid.rect(gp=gpar(fill="gray90")) # background
>>  par(plt=gridPLT())
>>  ## plot
>>  plot(1:10, 1:10, log="y", xlab="", ylab="",
>>   xaxt=if(i==2) "s" else "n", yaxt=if(j==1) "s" else "n")
>>  par(new=TRUE) # to be run after first plot
>>  upViewport()
>>  }
>> }
>> par(par.)
>> dev.off()
>>
>> __
>> R-help@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.
>>

__
R-help@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.


[R] Background color in a grid plot seems to interfere with plot()

2012-09-23 Thread Marius Hofert
Hi,

Why does the upper left panel (in the plot below) not have a gray background?

Cheers,

Marius


require(grid)
require(gridBase)

pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)

## set up the grid layout
gl <- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8, 8, 0.8), "cm"),
  heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
if(FALSE) grid.show.layout(gl)
pushViewport(viewport(layout=gl))

## plot data
par. <- par(no.readonly=TRUE) # save plot settings
for(i in 1:2) { # rows
i. <- if(i > 1) i+2 else i+1 # jumping over gaps
for(j in 1:2) { # columns
j. <- if(j > 1) j+2 else j+1 # jumping over gaps
pushViewport(viewport(layout.pos.row=i., layout.pos.col=j.))
grid.rect(gp=gpar(fill="gray90")) # background
par(plt=gridPLT())
## plot
plot(1:10, 1:10, log="y", xlab="", ylab="",
 xaxt=if(i==2) "s" else "n", yaxt=if(j==1) "s" else "n")
par(new=TRUE) # to be run after first plot
upViewport()
}
}
par(par.)
dev.off()

__
R-help@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.


Re: [R] grid: How to merge cells in grid.layout?

2012-09-23 Thread Marius Hofert
Ahh, now I see what you mean... Thanks, that indeed works. 

Cheers,

Marius

Marius Hofert  writes:

> Bert Gunter  writes:
>
>> Inline below.
>>
>> On Sun, Sep 23, 2012 at 1:41 AM, Marius Hofert
>>  wrote:
>>> Dear grid expeRts,
>>>
>>> I would like to create a layout with grid that looks like the following, 
>>> but with cells (1,1), (1,4), (4,1), and (4,4) removed and cells (2,1) and 
>>> (3,1) (and (4,2) and (4,3)) combined to one cell (so that contents can 
>>> easily be centered.
>>>
>>> How can this be achieved?
>>>
>>> require(grid)
>>> gl <- grid.layout(4, 4, widths=unit(c(1, 3, 3, 1), "cm"),
>>>   heights=unit(c(1, 3, 3, 1), "cm"))
>>> grid.show.layout(gl)
>>>
>>> My goal is to put 4 plots in the larger squares, create some labels in the 
>>> boxes
>>> (1,2), (1,3), (2,4), (3,4), and put common x-axis and y-axis labels in the
>>> (combined) boxes (2,1), (3,1) and (4,2), (4,3).
>>
>> Why don't the "layout.pos.row" and "layout.pos.col" arguments of
>> ?viewport not do exactly what you appear to want? Perhaps I
>> misunderstand, but I think what you want to do is just create your
>> layout as above and then push the viewports you want by suitably
>> setting these arguments, and then just draw your plots.
>
> ... but I will always have two sub-boxes instead of one single box below the
> x-axis and to the left of the y-axis. In a single box for the axis labels, one
> can easily center a label. But with two boxes, how do you determine the center
> of both? 
>
>>
>>
>>  If you're serious about using grid, Murrell's Graphics book is
>> essential and probably will clarify these issues for you (better than
>> I can, anyway).
>
> I know that, thanks for pointing it out. Unfortunately, there is no problem of
> the above type mentioned (afaik), that's why I asked.
>
>>
>>
>>>
>>> With layout() one can simply cbind/rbind boxes to produce the desired
>>> result. With grid.layout() this seems not be the case. Maybe the workflow is
>>> differently here to get the desired result.
>>
>> You appear to be mistaken. 
>
> I might have described it unsufficiently, but you can do the above with 
> layout()
> [I used that trick in many plots before]. The above-mentioned two boxes would
> get the same number, so would be treated as one plot region. I was hoping for
> something similar with grid.layout. 
>
> It is clear that you can always build your layout with "too many boxes" as a
> rectangular region and only address those viewports where plotting should take
> place. But I don't see how one could specify to plot in the center of two
> adjacent boxes of the same sizes so that the content looks "centered" with
> respect to both boxes (viewed as a single box).
>
>> From ?grid.layout:
>>
>> "This function must NOT be confused with the base R graphics function
>> layout. In particular, do not use layout in combination with Grid
>> graphics. The documentation for layout may provide some useful
>> information and this function should behave identically in comparable
>> situations. The grid.layout function has added the ability to specify
>> a broader range of units for row heights and column widths, and allows
>> for nested layouts (see viewport). "
>>
>> Cheers,
>> Bert
>>
>>>
>>> Cheers,
>>>
>>> Marius
>>>
>>> __
>>> R-help@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.
>

-- 
ETH Zurich
Dr. Marius Hofert
RiskLab, Department of Mathematics
HG E 65.2
Rämistrasse 101
8092 Zurich
Switzerland

Phone +41 44 632 2423
http://www.math.ethz.ch/~hofertj

__
R-help@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.


Re: [R] grid: How to merge cells in grid.layout?

2012-09-23 Thread Marius Hofert

Bert Gunter  writes:

> Inline below.
>
> On Sun, Sep 23, 2012 at 1:41 AM, Marius Hofert
>  wrote:
>> Dear grid expeRts,
>>
>> I would like to create a layout with grid that looks like the following, but 
>> with cells (1,1), (1,4), (4,1), and (4,4) removed and cells (2,1) and (3,1) 
>> (and (4,2) and (4,3)) combined to one cell (so that contents can easily be 
>> centered.
>>
>> How can this be achieved?
>>
>> require(grid)
>> gl <- grid.layout(4, 4, widths=unit(c(1, 3, 3, 1), "cm"),
>>   heights=unit(c(1, 3, 3, 1), "cm"))
>> grid.show.layout(gl)
>>
>> My goal is to put 4 plots in the larger squares, create some labels in the 
>> boxes
>> (1,2), (1,3), (2,4), (3,4), and put common x-axis and y-axis labels in the
>> (combined) boxes (2,1), (3,1) and (4,2), (4,3).
>
> Why don't the "layout.pos.row" and "layout.pos.col" arguments of
> ?viewport not do exactly what you appear to want? Perhaps I
> misunderstand, but I think what you want to do is just create your
> layout as above and then push the viewports you want by suitably
> setting these arguments, and then just draw your plots.

... but I will always have two sub-boxes instead of one single box below the
x-axis and to the left of the y-axis. In a single box for the axis labels, one
can easily center a label. But with two boxes, how do you determine the center
of both? 

>
>
>  If you're serious about using grid, Murrell's Graphics book is
> essential and probably will clarify these issues for you (better than
> I can, anyway).

I know that, thanks for pointing it out. Unfortunately, there is no problem of
the above type mentioned (afaik), that's why I asked.

>
>
>>
>> With layout() one can simply cbind/rbind boxes to produce the desired
>> result. With grid.layout() this seems not be the case. Maybe the workflow is
>> differently here to get the desired result.
>
> You appear to be mistaken. 

I might have described it unsufficiently, but you can do the above with layout()
[I used that trick in many plots before]. The above-mentioned two boxes would
get the same number, so would be treated as one plot region. I was hoping for
something similar with grid.layout. 

It is clear that you can always build your layout with "too many boxes" as a
rectangular region and only address those viewports where plotting should take
place. But I don't see how one could specify to plot in the center of two
adjacent boxes of the same sizes so that the content looks "centered" with
respect to both boxes (viewed as a single box).

> From ?grid.layout:
>
> "This function must NOT be confused with the base R graphics function
> layout. In particular, do not use layout in combination with Grid
> graphics. The documentation for layout may provide some useful
> information and this function should behave identically in comparable
> situations. The grid.layout function has added the ability to specify
> a broader range of units for row heights and column widths, and allows
> for nested layouts (see viewport). "
>
> Cheers,
> Bert
>
>>
>> Cheers,
>>
>> Marius
>>
>> __
>> R-help@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.

__
R-help@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.


[R] grid: How to merge cells in grid.layout?

2012-09-23 Thread Marius Hofert
Dear grid expeRts,

I would like to create a layout with grid that looks like the following, but 
with cells (1,1), (1,4), (4,1), and (4,4) removed and cells (2,1) and (3,1) 
(and (4,2) and (4,3)) combined to one cell (so that contents can easily be 
centered.

How can this be achieved?

require(grid)
gl <- grid.layout(4, 4, widths=unit(c(1, 3, 3, 1), "cm"),
  heights=unit(c(1, 3, 3, 1), "cm"))
grid.show.layout(gl)

My goal is to put 4 plots in the larger squares, create some labels in the boxes
(1,2), (1,3), (2,4), (3,4), and put common x-axis and y-axis labels in the
(combined) boxes (2,1), (3,1) and (4,2), (4,3).

With layout() one can simply cbind/rbind boxes to produce the desired
result. With grid.layout() this seems not be the case. Maybe the workflow is
differently here to get the desired result.

Cheers,

Marius

__
R-help@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.


Re: [R] How to determine R version?

2012-09-22 Thread Marius Hofert
Thanks, Berend, that works. 

Cheers,

Marius

Berend Hasselman  writes:

> On 22-09-2012, at 19:32, Marius Hofert wrote:
>
>> Hi,
>> 
>> What's the best approach to determine if a user uses an R version before 
>> 2.15.1
>> patched?
>> I know that the sessionInfo() command provides details, but I'm not sure how
>> the output of sessionInfo() is best used to determine R versions. This seems 
>> to
>> work, but a) there is certainly a better way and b) I'm not sure where the
>> "patched" will appear in the string. 
>> 
>> if(sessionInfo()$R.version$minor < "15.1") ...
>
> ?getRversion 
>
> is an option
>
> Berend
>

__
R-help@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.


[R] How to determine R version?

2012-09-22 Thread Marius Hofert
Hi,

What's the best approach to determine if a user uses an R version before 2.15.1
patched?
I know that the sessionInfo() command provides details, but I'm not sure how
the output of sessionInfo() is best used to determine R versions. This seems to
work, but a) there is certainly a better way and b) I'm not sure where the
"patched" will appear in the string. 

if(sessionInfo()$R.version$minor < "15.1") ...

Cheers,

Marius

__
R-help@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.


Re: [R] How to convert the output of tapply() so that it has the same order as the input?

2012-09-15 Thread Marius Hofert
Dear Bill,

Thanks a lot for your quick reply, that was exactly what I was looking for.

Cheers,

Marius

William Dunlap  writes:

> Does ave() do what you want?
>   y. <- ave(x$value, x$x1, x$x2, FUN=function(x)x)
>
> Bill Dunlap
> Spotfire, TIBCO Software
> wdunlap tibco.com
>
>

__
R-help@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.


[R] How to convert the output of tapply() so that it has the same order as the input?

2012-09-15 Thread Marius Hofert
Hi,

I try to apply a function to subsets of a data.frame. tapply() does the job, but
the as output, I am looking for a vector (not an array/matrix) ordered in the
same way as the original data, so I can simply cbind the result to the original
data.frame. Below is a minimal example.

I know that there are packages that can do these things easier, but I'm looking
for a fast solution not requiring additional packages. 

Cheers,

Marius


## data.frame
set.seed(1)
(x <- data.frame(x1=LETTERS[1:4], x2=1:2, value=runif(8)))

## apply a function to each subset combination of x1 and x2
y <- tapply(x$value, x[,-3], function(x) x)

## (trials of) transforming the output to be of the same type and order as 
x$value
(y. <- do.call(rbind, y)) # => wrong order
(y. <- do.call(cbind, y)) # => wrong order

## appending (that's the goal)
z <- x
z$value <- y.

__
R-help@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.


Re: [R] How to insert vertical space between lines of tables created with the R package 'tables'?

2012-09-08 Thread Marius Hofert


Duncan Murdoch  writes:

>
> The + means concatenation, so that spec says to put the RowFactor above the
> d*beta rows.  Not sure why that causes an error, but it's likely because 
> you've
> got the wrong number of items.
>
> This should work, but it doesn't give you the extra spacing properly. I didn't
> think anyone would want extra spacing on every level.  I'll put in a patch to
> fix it; look for an update on R-forge.
>
> tabular(RowFactor(d, spacing=1, space=0.5) * beta ~ group * mean *
> + Heading() * value, data=df)
>
>
> Duncan Murdoch
>

Thanks a lot, Duncan. 

In the minimal example, I have two variables (d and beta) that create "blocks"
of rows showing similar results. Assume you have three (say, d, beta, and
alpha in columns 1, 2, and 3, respectively). I typically separate blocks with 
the
same d by a larger space, then blocks with the same beta with a smaller space 
(and
blocks with the same alphas with no space). So this would look like:

tabular(RowFactor(d, spacing=2, space=0.5) * RowFactor(beta, spacing=2,
space=0.25) * alpha ~ group * mean * Heading() * value, data=df)

... with appropriate "spacing" arguments. I find this visually quite appealing. 

Cheers,

Marius

__
R-help@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.


[R] How to insert vertical space between lines of tables created with the R package 'tables'?

2012-09-08 Thread Marius Hofert
I have the data frame...

df <- cbind(expand.grid(d=as.factor(c(2,5)), n=c(100, 200),
beta=as.factor(c(0.2, 0.8)), group=LETTERS[1:2]), value=runif(16))

... which I would like to display in a table like ...

require(tables)
tabular(d * beta ~ group * mean * Heading() * value, data=df)

Now I would like to insert (vertical) space between every other line of the
table. I checked the manual and vignette of 'tables', but it only covers the
case when there is just one variable specified in the left-hand side of the
formula (so "to the left" of "~"). I tried to adapt the idea of using
RowFactor() ... 

tabular(RowFactor(1:4, "", spacing=2, space=0.5) + d * beta ~ group * mean *
Heading() * value, data=df)

... but obtain ... 

Error in `colnames<-`(`*tmp*`, value = "") : 
  length of 'dimnames' [2] not equal to array extent


Cheers,

Marius

__
R-help@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.


Re: [R] patchDVI: how to pass encoding of the .Rnw file?

2012-08-24 Thread Marius Hofert
Dear Duncan,

many thanks for helping. It works fine.

Cheers,

Marius

Duncan Murdoch  writes:

> On 12-08-19 3:47 PM, Marius Hofert wrote:
>> Dear Duncan,
>>
>> I recently asked a question concerning patchDVI on r-help, see
>>
>> ,
>> | https://stat.ethz.ch/pipermail/r-help/2012-August/321780.html
>> `
>>
>> Unfortunately, no one could help. I was wondering if you know a solution to 
>> the
>> above problem. Any hint is highly appreciated.
>
> Sorry, I'm writing this while offline, so I can't quote your message.
> The issue was that if the main .tex file uses \input to include another file,
> and that file needs to be processed by Sweave, then the usual encoding
> detection method (looking for \usepackage[utf8]{inputenc} or similar) won't
> work, because you can't put that line in the secondary file.
>
> The solution is the same as when using Sweave:  put a default encoding into
> the call to SweavePDF (or the similar functions).  For example, my editor
> always executes this command when asked to process a .Rnw file:
>
> patchDVI::SweavePDF('%2', stylepath=FALSE,
> preview="f:/SumatraPDF/SumatraPDF \x25s",
> encoding="utf8")
>
> The %2 is a place holder for the filename to process.  The preview argument
> invokes the PDF previewer that knows Synctex; the stylepath and encoding
> arguments are passed to Sweave.  Because I chose encoding="utf8", Sweave
> will assume that encoding as the default for files.  Another encoding  can be
> explicitly declared.
>
> When I have multi-file projects, I make use of .TexRoot and .SweaveFiles
> in each of the files so I can make the whole project each time;
> see the patchDVI vignette (section 6) for details of how they work.
>
> I think you also asked how to do this in Emacs; I've got no idea about that.
>
> Duncan Murdoch

__
R-help@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.


[R] How to call patchDVI::SweavePDF on an .Rnw which is not the master file?

2012-08-16 Thread Marius Hofert
Dear expeRts,

I have a master file master.tex containing the preamble and which inputs (via
\input{chapter01}, \input{chapter02}, ...) chapters. The chapters are .Rnw
files. My goal is to use patchDVI::SweavePDF to compile the chapters (say,
chapter.Rnw) individually (each chapter starts with sourcing Sweave preliminary
settings).

The first problem is the following. If I execute (in the shell)

,
| Rscript -e "patchDVI::SweavePDF('chapter.Rnw')"
`

I obtain

,
| Loading required package: grDevices
| Error: ‘chapter.Rnw’ is not ASCII and does not declare an encoding
| Execution halted
`

Normally one uses \usepackage[utf8]{inputenc} to solve this problem. However, I
can't put this into chapter.Rnw since it is only allowed in the preamble, so in
master.tex. But there it has no effect. The question is how to solve this. By
looking at 'standard Sweave', I found the call

,
| R CMD Sweave --encoding=utf-8 chapter.Rnw
`

which works fine. But I don't know how to pass the --encoding=utf-8 option to
Rscript or how to use R CMD ... to solve the problem.

The second (follow-up) problem should then be simple: How to call that from
Emacs. Ideally, something like the following should work, but one somehow needs
too many ", ', ... to create the string "Rscript ...":

,
| (add-hook 'Rnw-mode-hook
| (lambda ()
|   (add-to-list 'TeX-command-list
|'("SweavePDF" "Rscript -e 'patchDVI::SweavePDF('%s', 
and-other-options)"   
|  TeX-run-command nil t :help "Run SweavePDF") t); 
TODO: not working yet
|   (add-to-list 'TeX-command-list
|'("Sweave" "R CMD Sweave --encoding=utf-8 %s"
|  TeX-run-command nil t :help "Run Sweave") t)
|   (add-to-list 'TeX-command-list
|'("Stangle" "R CMD Stangle --encoding=utf-8 %s"
|  TeX-run-command nil t :help "Run Stangle") t)
|   (add-to-list 'TeX-command-list
|'("make" "make" TeX-run-command nil t :help "Run 
make") t)
|   (setq TeX-command-default "SweavePDF")))
`

If anybody already has such a setup, I'd be happy to know about it.

Cheers,

Marius

__
R-help@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.


Re: [R] Hmisc's latex: na.blank and grouping not working as expected

2012-05-02 Thread Marius Hofert
I forgot to say what 'rmNames' is:

rmNames <- function(x) {x[c(FALSE, x[-1]==x[-length(x)])] <- ""; x} 

With 

rmNames <- function(x) {x[c(FALSE, x[-1]==x[-length(x)])] <- NA; x} 

the option na.blank=TRUE works as expected. Also, the two empty columns are 
inserted due to "cgroup", but I don't know how to avoid this.

On 2012-05-02, at 09:26 , Marius Hofert wrote:

> Dear expeRts,
> 
> Why does na.blank=TRUE not replace the NA's in the following LaTeX table?
> 
> x <- matrix(1:72, ncol=4, nrow=8)
> colnames(x) <- c("gr1.sgr1", "gr1.sgr2", "gr2.sgr1", "gr2.sgr2")
> rn <- apply(expand.grid(beta=c(0.25, 0.75), n=c(100, 500), d=c(10, 100))[, 
> 3:1], 2, rmNames)
> x <- cbind(rn, x) # append columns containing the row labels
> x[2,5] <- NA
> stopifnot(is.na(x[2,5]))
> 
> require(Hmisc)
> latex(x,
>  file="",
>  na.blank=TRUE,
>  rowlabel=c("d", "n", "beta"),
>  booktabs=TRUE)
> 
> In the end, I would like to have the columns displayed in groups like this:
> 
>Group 1 Group 2
> d   n   beta   Sub-group 1   Sub-group 2   Sub-group 1   Sub-group 2
> 10  100 0.25   1 9
>0.75   2
>500 0.25   310
>0.75   411 ...   ...
> 100 100 0.25   512
>0.75   613
>500 0.25   7...
>0.75   8
> 
> If anybody knows how to do this, please let me know :-) This is (one of) my 
> trial(s):
> 
> latex(x,
>  file="",
>  cgroup=c("", "Group 1", "Group 2"),
>  n.cgroup=c(3, 2, 2),
>  na.blank=TRUE,
>  rowlabel=c("d", "n", "beta"),
>  booktabs=TRUE)
> 
> Why are there two empty columns inserted and the table has suddenly 9 columns 
> instead of 7?
> 
> Cheers,
> 
> Marius
> 

__
R-help@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.


[R] Hmisc's latex: na.blank and grouping not working as expected

2012-05-02 Thread Marius Hofert
Dear expeRts,

Why does na.blank=TRUE not replace the NA's in the following LaTeX table?

x <- matrix(1:72, ncol=4, nrow=8)
colnames(x) <- c("gr1.sgr1", "gr1.sgr2", "gr2.sgr1", "gr2.sgr2")
rn <- apply(expand.grid(beta=c(0.25, 0.75), n=c(100, 500), d=c(10, 100))[, 
3:1], 2, rmNames)
x <- cbind(rn, x) # append columns containing the row labels
x[2,5] <- NA
stopifnot(is.na(x[2,5]))

require(Hmisc)
latex(x,
  file="",
  na.blank=TRUE,
  rowlabel=c("d", "n", "beta"),
  booktabs=TRUE)

In the end, I would like to have the columns displayed in groups like this:

Group 1 Group 2
d   n   beta   Sub-group 1   Sub-group 2   Sub-group 1   Sub-group 2
10  100 0.25   1 9
0.75   2
500 0.25   310
0.75   411 ...   ...
100 100 0.25   512
0.75   613
500 0.25   7...
0.75   8

If anybody knows how to do this, please let me know :-) This is (one of) my 
trial(s):

latex(x,
  file="",
  cgroup=c("", "Group 1", "Group 2"),
  n.cgroup=c(3, 2, 2),
  na.blank=TRUE,
  rowlabel=c("d", "n", "beta"),
  booktabs=TRUE)

Why are there two empty columns inserted and the table has suddenly 9 columns 
instead of 7?

Cheers,

Marius

__
R-help@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.


Re: [R] How to colorize the panel backgrounds of pairs()?

2012-03-02 Thread Marius Hofert
Okay, one simply has to use label.pos=0.5 in pairs() to get the correct 
behavior.


On 2012-03-02, at 09:10 , Marius Hofert wrote:

> Dear Ilai,
> 
> I tried to also adjust the diagonal panels. However, the variable names are 
> not
> positioned correctly anymore. Do you know a solution?
> 
> Cheers,
> 
> Marius
> 
> count <- 0
> mypanel <- function(x, y, ...){
>   count <<- count+1
>   bg <- if(count %in% c(1,4,9,12)) "#FDFF65" else "transparent"
>   ll <- par("usr")
>   rect(ll[1], ll[3], ll[2], ll[4], col=bg)
>   points(x, y, cex=0.5)
> }
> 
> mydiag.panel <- function(x, ...){
>   ll <- par("usr")
>   rect(ll[1], ll[3], ll[2], ll[4], col="#FDFF65")
> }
> 
> U <- matrix(runif(4*500), ncol=4)
> pairs(U, panel=mypanel, diag.panel=mydiag.panel)
> 
> 
> Marius Hofert  writes:
> 
>> Indeed, precisely what I was looking for. Many thanks, Ilai.
>> 
>> ilai  writes:
>> 
>>> par('bg') is not what you are looking for - it will set the bg of the
>>> whole graphic device, not panels. I think you want:
>>> count <- 0
>>> mypanel <- function(x, y, ...){
>>>   count <<- count+1
>>>   ll<- par('usr')
>>>   if(count %in% c(1,4,9,12)) bg<- "#FDFF65"
>>>   else bg<- 'transparent'
>>>   rect(ll[1],ll[3],ll[2],ll[4],col=bg)
>>>   points(x, y, cex=0.5)
>>> }
>>> 
>>> Cheers
>>> 
>>> On Thu, Mar 1, 2012 at 4:49 PM, Marius Hofert
>>>  wrote:
>>>> Dear expeRts,
>>>> 
>>>> I would like to colorize the backgrounds of a pairs plot according to the
>>>> respective panel number. Here is what I tried (without success):
>>>> 
>>>> count <- 0
>>>> mypanel <- function(x, y, ...){
>>>>count <<- count+1
>>>>bg. <- if(count %in% c(1,4,9,12)) "#FDFF65" else NA
>>>>points(x, y, cex=0.5, bg=bg)
>>>> }
>>>> 
>>>> U <- matrix(runif(4*500), ncol=4)
>>>> pairs(U, panel=mypanel)
>>>> 
>>>> I also tried to set par(bg=bg.) before the call to points(), but that 
>>>> didn't
>>>> work either. The only thing I found is that "bg=" can be used to fill 
>>>> certain
>>>> plot symbols, but I would like to colorize the background of each panel, 
>>>> not
>>>> the drawn circles.
>>>> 
>>>> Cheers,
>>>> 
>>>> Marius
>>>> 
>>>> __
>>>> R-help@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.

__
R-help@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.


Re: [R] How to colorize the panel backgrounds of pairs()?

2012-03-02 Thread Marius Hofert
Dear Ilai,

I tried to also adjust the diagonal panels. However, the variable names are not
positioned correctly anymore. Do you know a solution?

Cheers,

Marius

count <- 0
mypanel <- function(x, y, ...){
   count <<- count+1
   bg <- if(count %in% c(1,4,9,12)) "#FDFF65" else "transparent"
   ll <- par("usr")
   rect(ll[1], ll[3], ll[2], ll[4], col=bg)
   points(x, y, cex=0.5)
}

mydiag.panel <- function(x, ...){
   ll <- par("usr")
   rect(ll[1], ll[3], ll[2], ll[4], col="#FDFF65")
}

U <- matrix(runif(4*500), ncol=4)
pairs(U, panel=mypanel, diag.panel=mydiag.panel)


Marius Hofert  writes:

> Indeed, precisely what I was looking for. Many thanks, Ilai.
>
> ilai  writes:
>
>> par('bg') is not what you are looking for - it will set the bg of the
>> whole graphic device, not panels. I think you want:
>> count <- 0
>> mypanel <- function(x, y, ...){
>>count <<- count+1
>>ll<- par('usr')
>>if(count %in% c(1,4,9,12)) bg<- "#FDFF65"
>>else bg<- 'transparent'
>>rect(ll[1],ll[3],ll[2],ll[4],col=bg)
>>points(x, y, cex=0.5)
>> }
>>
>> Cheers
>>
>> On Thu, Mar 1, 2012 at 4:49 PM, Marius Hofert
>>  wrote:
>>> Dear expeRts,
>>>
>>> I would like to colorize the backgrounds of a pairs plot according to the
>>> respective panel number. Here is what I tried (without success):
>>>
>>> count <- 0
>>> mypanel <- function(x, y, ...){
>>>    count <<- count+1
>>>    bg. <- if(count %in% c(1,4,9,12)) "#FDFF65" else NA
>>>    points(x, y, cex=0.5, bg=bg)
>>> }
>>>
>>> U <- matrix(runif(4*500), ncol=4)
>>> pairs(U, panel=mypanel)
>>>
>>> I also tried to set par(bg=bg.) before the call to points(), but that didn't
>>> work either. The only thing I found is that "bg=" can be used to fill 
>>> certain
>>> plot symbols, but I would like to colorize the background of each panel, not
>>> the drawn circles.
>>>
>>> Cheers,
>>>
>>> Marius
>>>
>>> __
>>> R-help@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.

__
R-help@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.


[R] How to colorize the panel backgrounds of pairs()?

2012-03-01 Thread Marius Hofert
Dear expeRts,

I would like to colorize the backgrounds of a pairs plot according to the 
respective panel number. Here is what I tried (without success):

count <- 0
mypanel <- function(x, y, ...){
count <<- count+1
bg. <- if(count %in% c(1,4,9,12)) "#FDFF65" else NA
points(x, y, cex=0.5, bg=bg)
}

U <- matrix(runif(4*500), ncol=4)
pairs(U, panel=mypanel)

I also tried to set par(bg=bg.) before the call to points(), but that didn't 
work either. The only thing I found is that "bg=" can be used to fill certain 
plot symbols, but I would like to colorize the background of each panel, not 
the drawn circles.

Cheers,

Marius

__
R-help@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.


[R] Fwd: How to access the panel rows/columns in pairs()?

2012-01-21 Thread Marius Hofert
okay, I found something. Not very elegant, but it does the job:

## generate data
U <- matrix(runif(4000), ncol=4)

## define panel function for colorizing the panels
cols <- c("blue", "black", "black",
  "blue", "black", "black",
  "black", "black", "green",
  "black", "black", "green")
count <- 0
mypanel <- function(x, y, ...){
count <<- count + 1
print(count)
points(x, y, cex=0.5, col=cols[count]) 
}

## scatter plot matrix
pairs(U, panel=mypanel)

__
R-help@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.


[R] How to access the panel rows/columns in pairs()?

2012-01-21 Thread Marius Hofert
Hi,

I would like to colorize certain panels in the pairs plot below with certain 
colors. How can access the panel row and column in a pairs plot to achieve this?

Cheers,

Marius


## generate data
U <- matrix(runif(4000), ncol=4)

## define panel function for colorizing the panels
mypanel <- function(x, y, ...){
points(x, y, cex=0.5, col="blue") # giving every panel the same color is 
easy; how can I get different colors for different panels, say, gray for the 
(2,3)-panel?
}

## scatter plot matrix
pairs(U, panel=mypanel)

__
R-help@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.


Re: [R] How to color a region in a contour plot with the contour being the boundary?

2012-01-03 Thread Marius Hofert
I was hoping for a solution without lattice. 
But it solves the problem, thanks Jean.

Cheers,

Marius


On 2012-01-03, at 19:06 , Jean V Adams wrote:

> 
> Try the levelplot() function in package lattice. 
> 
> library(lattice) 
> 
> dat <- expand.grid(x=x, y=y) 
> dat$z <- pmax(f(dat$x) + f(dat$y) - 10, 0) 
> 
> levelplot(z ~ x * y, dat, 
> at=c(-1, 0.02, 1, 5, 10, 20, 50, 500, 900), 
> labels=TRUE, contour=TRUE, colorkey=FALSE, 
> col.regions=gray(c(0.2, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1))) 
> 
> Jean 
> 
> 
> Marius Hofert wrote on 12/31/2011 05:02:22 AM:
> 
> > Dear expeRts,
> > 
> > I would like to color a certain region in a levelplot. The region 
> > for z <= 0.02 should have a dark gray color. Below is a minimal 
> > example. It almost does what I want, but The region between z=0.02 
> > and z=1 is also colored in dark gray (instead of just the region for
> > z <= 0.02).
> > How can I solve this?
> > 
> > Cheers,
> > 
> > Marius
> > 
> > 
> > ## z values for given x and y
> > f <- function(x) 4*((1-x)^(-1/2)-1)
> > eps <- 1e-12
> > x <- y <- seq(eps, 1-eps, length.out=500)
> > z <- outer(x, y, FUN=function(x, y) pmax(f(x) + f(y) - 10, 0))
> > 
> > ## determine colors
> > zcols <- c(gray(0.2), gray(seq(0.5, 1, length.out=50)), rep
> > ("#FF", max(z)-51)) # colors with dark gray in the beginning for
> > z <= 0.02 and many whites for z > 50
> > 
> > ## trial 1
> > pdf(file="levelplot1.pdf", width=6, height=6)
> > image(x, y, z, xaxs="r", yaxs="r", col=zcols)
> > contour(x, y, z, levels=c(0.02, 1, 5, 10, 20, 50, 500), add=TRUE)
> > dev.off()
> > 
> > ## trial 2
> > pdf(file="levelplot2.pdf", width=6, height=6)
> > image(x, y, z, xaxs="r", yaxs="r", col=zcols, oldstyle=TRUE)
> > contour(x, y, z, levels=c(0.02, 1, 5, 10, 20, 50, 500), add=TRUE)
> > dev.off()

__
R-help@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.


[R] How to color a region in a contour plot with the contour being the boundary?

2011-12-31 Thread Marius Hofert
Dear expeRts,

I would like to color a certain region in a levelplot. The region for z <= 0.02 
should have a dark gray color. Below is a minimal example. It almost does what 
I want, but The region between z=0.02 and z=1 is also colored in dark gray 
(instead of just the region for z <= 0.02).
How can I solve this?

Cheers,

Marius


## z values for given x and y
f <- function(x) 4*((1-x)^(-1/2)-1)
eps <- 1e-12
x <- y <- seq(eps, 1-eps, length.out=500)
z <- outer(x, y, FUN=function(x, y) pmax(f(x) + f(y) - 10, 0))

## determine colors
zcols <- c(gray(0.2), gray(seq(0.5, 1, length.out=50)), rep("#FF", 
max(z)-51)) # colors with dark gray in the beginning for z <= 0.02 and many 
whites for z > 50

## trial 1
pdf(file="levelplot1.pdf", width=6, height=6)
image(x, y, z, xaxs="r", yaxs="r", col=zcols)
contour(x, y, z, levels=c(0.02, 1, 5, 10, 20, 50, 500), add=TRUE)
dev.off()

## trial 2
pdf(file="levelplot2.pdf", width=6, height=6)
image(x, y, z, xaxs="r", yaxs="r", col=zcols, oldstyle=TRUE)
contour(x, y, z, levels=c(0.02, 1, 5, 10, 20, 50, 500), add=TRUE)
dev.off()

__
R-help@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.


[R] acast: how to obtain names?

2011-11-18 Thread Marius Hofert
Hi,

After applying acast() I typically have to adjust the names of the array by 
hand. Is there any way to tell acast to do this automatically?

Cheers,

Marius

require(reshape2)
(df <- data.frame(a=c("a1","a2"), b=c("b1","b2"), c=c("c1","c2")))
a.df <- acast(df, a~b, value_var="c")
names(dimnames(a.df)) # => NULL; would be nice to get the following:
names(dimnames(a.df)) <- c("a", "b")
a.df

__
R-help@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.


Re: [R] Rgl and plotmath symbols (via sprites): a trial

2011-09-09 Thread Marius Hofert
Dear Duncan,

attached my next trial. It seems to work :-) Unfortunately, not the printing to 
pdf. Not getting a high-quality pdf is certainly one of the major drawbacks. If 
anybody knows how to fix that, please let me know. Even when generating the 
labels "by hand" (with grid), the code is less than setting up a nice lattice 
wireframe plot... so that makes rgl a great tool. 

Cheers,

Marius


require(rgl)
require(grid)

s <- seq(0, 1, length.out=21)
M <- function(u) apply(u, 1, min)
u <- s
v <- s
z <- outer(u, v, function(u,v) M(cbind(u,v)))

## create z-axis label
png("zlabel.png", bg="transparent", width=500, height=500)
grid.newpage()
pushViewport(plotViewport(c(1,1,1,1)))
print(grid.text(expression(W(u[1],u[2])==c), rot=90, gp=gpar(fontsize=85)))
popViewport()
dev.off()

## plot
persp3d(u, v, z, aspect="iso", front="line", lit=FALSE, axes=FALSE, xlab="", 
ylab="", zlab="") 
axes3d(edges=c('x--','y--','z+-')) 
par3d(ignoreExtent=TRUE)
sprites3d(1.4,-0.2,0.5, radius=0.5, lit=FALSE, textype="alpha", 
texture="zlabel.png")
par3d(windowRect=c(0,0,600,600), zoom=1.6) 
rgl.snapshot("W.png", fmt="png") # print to file



On 2011-09-09, at 17:26 , Duncan Murdoch wrote:

> On 09/09/2011 11:10 AM, Marius Hofert wrote:
>> Dear all,
>> 
>> Below is some code where I try to get plotmath symbols in an rgl plot. Duncan
>> Murdoch kindly suggested to use a "sprite" for this. As you can see, on can 
>> get
>> it to work, but my knowledge about grid and rgl is too limited to perfectly
>> solve the problem.
>> 1) As you can see (please rotate the plot a little bit so that (0,0,0) is 
>> "in front"),
>> the quality of the .png seems poor. Can this be improved?
> 
> Generally plotting much larger and shrinking is the way to do this.

>> 2) When I print the file to a .pdf, the label is just a black square... I 
>> assume
>> one then has to print to png again... hmmm... not perfect.
> 
> rgl.postscript has a lot of limitations.  This one may be unavoidable.
>> 3) Some parts of the z-axis are covered by the label. How can this be fixed?
>> The problem seems to be that sprites have a radius. Specifying a rectangle 
>> would
>> be better here, but I am not sure how this works (or even if it does).
>> 
> 
> I think I don't see this in Windows, which shows the black text for the label 
> on a transparent background.  Do you see a solid background?  Or is it just 
> the positioning?  The tick marks go out at an angle, whereas your sprite 
> seems to be in line with the zy plane.  I would increase the x value to 
> something like 1.4 to place it properly.  (Just tried that, and I think I see 
> the problem you had:  the new sprite is obscured by the old one.
> You may need to play with the depth_test or depth_mask material properties.  
> Not sure if those are visible on CRAN; if not, try the R-forge version.)
> 
> The other thing I'd recommend is that before plotting the sprite, you run 
> par3d(ignoreExtent=TRUE) (and then set it back to the original value 
> afterwards).  This will stop the label from affecting the bounding box of the 
> plot.
> 
> Duncan Murdoch
> 
> 
>> Cheers,
>> 
>> Marius
>> 
>> 
>> 
>> 
>> 
>> require(rgl)
>> require(grid)
>> 
>> s<- seq(0, 1, length.out=21)
>> M<- function(u) apply(u, 1, min)
>> u<- s
>> v<- s
>> z<- outer(u, v, function(u,v) M(cbind(u,v)))
>> 
>> ## create z-axis label
>> png("zlabel.png", bg="transparent", width=70, height=70)
>> grid.newpage()
>> pushViewport(plotViewport(c(1,1,1,1)))
>> print(grid.text(expression(W(u[1],u[2])==c),rot=90))
>> popViewport()
>> dev.off()
>> 
>> ## plot
>> persp3d(u, v, z, aspect="iso", front="line", lit=FALSE, axes=FALSE, xlab="",
>> ylab="", zlab="")
>> axes3d(edges=c('x--','y--','z+-'))
>> sprites3d(1,-0.4,0.65, radius=0.5, lit=FALSE, textype="alpha", 
>> texture="zlabel.png")
>> rgl.postscript("W.pdf", fmt="pdf") # print to file
>> 
>> # par3d(c("userMatrix", "zoom", "FOV")):
>> #
>> # $userMatrix
>> #[,1]   [,2]   [,3] [,4]
>> # [1,]  0.7262191 -0.6867201 0.031957750
>> # [2,]  0.2750087  0.3328032 0.902004660
>> # [3,] -0.6300603 -0.6462642 0.430542020
>> # [4,]  0.000  0.000 0.1
>> #
>> # $zoom
>> # [1] 1
>> #
>> # $FOV
>> # [1] 30
>> 
>> 
>> 
>> 
> 

__
R-help@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.


Re: [R] rgl: axis/viewport/box problems in persp3d()

2011-09-09 Thread Marius Hofert
Dear Duncan,

thanks a lot. 
Is it possible to rotate the label drawn by mtext3d, say, by 90 degrees? [a 
"rot=90" did not help]

Cheers,

Marius

On 2011-09-09, at 14:32 , Duncan Murdoch wrote:

> On 09/09/2011 8:02 AM, Marius Hofert wrote:
>> Dear Duncan,
>> 
>> thanks for your quick response.
>> Below is my second trial. I had to use mtext3d to place the label for the 
>> z-axis
>> at the new axis where the ticks are drawn (if there's a simpler solution, 
>> please
>> let me know). Was the usage of rgl.viewpoint meant this way?
> 
> I would have used par3d(zoom=pl$zoom, ... ) instead of rgl.viewpoint, but it 
> probably gives the same result.  You'd have to check the sources.
> 
>>  It is nice to
>> adjust the rotation of the plotted object by hand but then I want to make 
>> sure
>> the subsequent plot(s) have precisely the same rotation.
>> 
>> Okay, great.
>> 
>> One more thing I am wondering is: I tried to pass through arguments like
>> marklen or expand to rgl.bbox/bbox3d. Is anything like this possible? I 
>> would like
>> to change the length of the axis ticks.
> 
> You can use marklen in bbox3d, but it won't affect the axes that were drawn 
> with axes3d.  This is something that has been on my todo-list for a long 
> time, uniting the two different ways of drawing axes (static ones from 
> axes3d, dynamic ones from bbox3d).  To modify the static tick length, you'll 
> need to modify the source to axis3d.
>> Cheers&  many thanks,
>> 
>> Marius
>> 
>> PS: I read somewhere that plotmath-expressions are not available in rgl. Is 
>> there
>> an update on this? I know it may be very difficult to implement this, I'm 
>> just
>> wondering if there is an update/workaround on this (?)
> 
> No, unfortunately not.   That's also on my todo-list, but fairly far down.  
> (I wouldn't implement plotmath in rgl; I would implement a standard graphics 
> driver in rgl, so all graphics functions could draw to a plane in 3d space.  
> But that's really a lot of work.)
> 
> Duncan Murdoch
> 
>> require(rgl)
>> s<- seq(0, 1, length.out=21)
>> M<- function(u) apply(u, 1, min)
>> u<- s
>> v<- s
>> z<- outer(u, v, function(u,v) M(cbind(u,v)))
>> persp3d(u, v, z, aspect="iso", front="line", lit=FALSE, axes=FALSE, xlab="",
>> ylab="", zlab="")
>> axes3d(edges=c('x--','y--','z+-')) # label the right axes
>> title3d(xlab="x", ylab="y", zlab="") # put in axes labels [z is wrong]
>> mtext3d("z", edge='z+-', line=2) # put in z-axis label by hand
>> par3d(windowRect=c(0,0,480,480), zoom=1.2) # use zoom to get everything on 
>> the viewport; then adjust rotation by hand
>> pl<- par3d(c("userMatrix", "zoom", "FOV")) # record for use in other plots
>> rgl.postscript("myplot.pdf", fmt="pdf") # print to file
>> rgl.viewpoint(zoom=pl$zoom, fov=pl$FOV, userMatrix=pl$userMatrix, 
>> interactive=FALSE) # set the viewpoint for the next plot to make sure it 
>> looks the same
>> 
>> On 2011-09-09, at 12:41 , Duncan Murdoch wrote:
>> 
>> >  On 11-09-09 6:18 AM, Marius Hofert wrote:
>> >>  Dear expeRts,
>> >>
>> >>  I am a new user of rgl, below is my first trial to plot a simple 
>> >> function in 3d.
>> >>  I managed to put the axes in the right locations, but:
>> >>  (1) The xlab, ylab, and zlab arguments are ignored; how can I put in 
>> >> axes labels?
>> >
>> >  Those are documented on the axes3d page, but are arguments to title3d, 
>> > not axes3d.  So add title3d(xlab="x", etc.
>> >
>> >>  (2) Since I removed the axes in persp3d() the viewport is too small; is 
>> >> it possible
>> >>  to keep the size of the viewport?
>> >
>> >  You can manually adjust it to your taste, then write down the value of 
>> > par3d("zoom").  Later you can reproduce the resizing by calling 
>> > par3d(zoom=  ).
>> >
>> >
>> >>  (3) The box is not correctly drawn, there are two "holes", one in 
>> >> (0,0,1) and one
>> >>  in (1,1,0); how can I fix that?
>> >
>> >  That happens because OpenGL has a limit on the range of depths that can 
>> > be displayed, and the corners of the box have been adjusted to be too 
>> > close or far. 

Re: [R] rgl: axis/viewport/box problems in persp3d()

2011-09-09 Thread Marius Hofert
Dear Duncan,

thanks for your quick response. 
Below is my second trial. I had to use mtext3d to place the label for the 
z-axis 
at the new axis where the ticks are drawn (if there's a simpler solution, please
let me know). Was the usage of rgl.viewpoint meant this way? It is nice to 
adjust the rotation of the plotted object by hand but then I want to make sure
the subsequent plot(s) have precisely the same rotation. 

Okay, great. 

One more thing I am wondering is: I tried to pass through arguments like
marklen or expand to rgl.bbox/bbox3d. Is anything like this possible? I would 
like
to change the length of the axis ticks.

Cheers & many thanks,

Marius

PS: I read somewhere that plotmath-expressions are not available in rgl. Is 
there
an update on this? I know it may be very difficult to implement this, I'm just 
wondering if there is an update/workaround on this (?)

require(rgl)
s <- seq(0, 1, length.out=21)
M <- function(u) apply(u, 1, min)
u <- s
v <- s
z <- outer(u, v, function(u,v) M(cbind(u,v)))
persp3d(u, v, z, aspect="iso", front="line", lit=FALSE, axes=FALSE, xlab="", 
ylab="", zlab="") 
axes3d(edges=c('x--','y--','z+-')) # label the right axes
title3d(xlab="x", ylab="y", zlab="") # put in axes labels [z is wrong]
mtext3d("z", edge='z+-', line=2) # put in z-axis label by hand
par3d(windowRect=c(0,0,480,480), zoom=1.2) # use zoom to get everything on the 
viewport; then adjust rotation by hand
pl <- par3d(c("userMatrix", "zoom", "FOV")) # record for use in other plots
rgl.postscript("myplot.pdf", fmt="pdf") # print to file
rgl.viewpoint(zoom=pl$zoom, fov=pl$FOV, userMatrix=pl$userMatrix, 
interactive=FALSE) # set the viewpoint for the next plot to make sure it looks 
the same

On 2011-09-09, at 12:41 , Duncan Murdoch wrote:

> On 11-09-09 6:18 AM, Marius Hofert wrote:
>> Dear expeRts,
>> 
>> I am a new user of rgl, below is my first trial to plot a simple function in 
>> 3d.
>> I managed to put the axes in the right locations, but:
>> (1) The xlab, ylab, and zlab arguments are ignored; how can I put in axes 
>> labels?
> 
> Those are documented on the axes3d page, but are arguments to title3d, not 
> axes3d.  So add title3d(xlab="x", etc.
> 
>> (2) Since I removed the axes in persp3d() the viewport is too small; is it 
>> possible
>> to keep the size of the viewport?
> 
> You can manually adjust it to your taste, then write down the value of 
> par3d("zoom").  Later you can reproduce the resizing by calling par3d(zoom= 
>  ).
> 
> 
>> (3) The box is not correctly drawn, there are two "holes", one in (0,0,1) 
>> and one
>> in (1,1,0); how can I fix that?
> 
> That happens because OpenGL has a limit on the range of depths that can be 
> displayed, and the corners of the box have been adjusted to be too close or 
> far.  This is arguably a bug in rgl, but it's sometimes a feature.
> 
> What I'd suggest is that you don't use rgl.viewpoint, you just manually 
> adjust the display as you like, without making it quite as extreme, then 
> record the values of par3d(c("userMatrix", "zoom", "FOV")); those control the 
> viewpoint.
> 
> Duncan Murdoch
> 
>> 
>> Cheers,
>> 
>> Marius
>> 
>> 
>> require(rgl)
>> s<- seq(0, 1, length.out=21)
>> M<- function(u) apply(u, 1, min)
>> u<- s
>> v<- s
>> z<- outer(u, v, function(u,v) M(cbind(u,v)))
>> persp3d(u, v, z, aspect="iso", front="line", lit=FALSE, axes=FALSE, xlab="",
>> ylab="", zlab="")
>> axes3d(edges=c('x--','y--','z+-'), xlab="x", ylab="y", zlab="z")
>> par3d(windowRect=c(0,0,480,480))
>> 
>> R1<- rotationMatrix(-55*pi/180, 1,0,0)
>> R3<- rotationMatrix(50*pi/180, 0,0,1)
>> R<- R1 %*% R3
>> rgl.viewpoint(interactive=TRUE, userMatrix=R) # rotate
>> rgl.postscript("myplot.pdf", fmt="pdf")
>> __
>> R-help@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.
> 

__
R-help@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.


[R] rgl: axis/viewport/box problems in persp3d()

2011-09-09 Thread Marius Hofert
Dear expeRts,

I am a new user of rgl, below is my first trial to plot a simple function in 
3d. 
I managed to put the axes in the right locations, but:
(1) The xlab, ylab, and zlab arguments are ignored; how can I put in axes 
labels?
(2) Since I removed the axes in persp3d() the viewport is too small; is it 
possible
to keep the size of the viewport?
(3) The box is not correctly drawn, there are two "holes", one in (0,0,1) and 
one
in (1,1,0); how can I fix that?

Cheers,

Marius


require(rgl)
s <- seq(0, 1, length.out=21)
M <- function(u) apply(u, 1, min)
u <- s
v <- s
z <- outer(u, v, function(u,v) M(cbind(u,v)))
persp3d(u, v, z, aspect="iso", front="line", lit=FALSE, axes=FALSE, xlab="", 
ylab="", zlab="") 
axes3d(edges=c('x--','y--','z+-'), xlab="x", ylab="y", zlab="z")
par3d(windowRect=c(0,0,480,480))

R1 <- rotationMatrix(-55*pi/180, 1,0,0) 
R3 <- rotationMatrix(50*pi/180, 0,0,1)
R <- R1 %*% R3
rgl.viewpoint(interactive=TRUE, userMatrix=R) # rotate
rgl.postscript("myplot.pdf", fmt="pdf")
__
R-help@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.


Re: [R] Best way/practice to create a new data frame from two given ones with last column computed from the two data frames?

2011-08-18 Thread Marius Hofert
Dear all,

okay, I found a one liner based on mutate:

(df3 <- mutate(df1, Value=Value[order(Year,Group)] / df2[with(df2, 
order(Year,Group)),"Value"]))

Cheers,

Marius

On 2011-08-18, at 20:41 , Marius Hofert wrote:

> Dear expeRts,
> 
> What is the best approach to create a third data frame from two given ones, 
> when
> the new/third data frame has last column computed from the last columns of 
> the two given
> data frames?
> 
> ## Okay, sounds complicated, so here is an example. Assume we have the two 
> data frames:
> df1 <- data.frame(Year=rep(2001:2010, each=2), Group=c("Group 1","Group 2"), 
> Value=1:20)
> df2 <- data.frame(Year=rep(2001:2010, each=2), Group=c("Group 1","Group 2"), 
> Value=21:40)
> 
> ## To make this a bit more fun, let's say the order of elements is 
> different...
> (df1 <- df1[sample(1:nrow(df1)),])
> (df2 <- df2[sample(1:nrow(df2)),])
> 
> ## Now I would like to create a third data frame that has "Year" in column 
> one, 
> ## "Group" in column two, and each entry of column three should consist of 
> the 
> ## corresponding entry in df1 divided by the one in df2. 
> 
> ## To achieve this, one could do:
> df3 <- df1[with(df1, order(Year,Group)),]
> df3$Value <- df3$Value/df2[with(df2, order(Year,Group)),]$Value
> colnames(df3)[3] <- "New Value" # typically, the column name changes 
> 
> ## or one could do:
> df3 <- df1[with(df1, order(Year,Group)), -ncol(df1)]
> df3 <- cbind(df3, "New Value"=df1[with(df1, 
> order(Year,Group)),]$Value/df2[with(df2, order(Year,Group)),]$Value)
> 
> ## Is there a more elegant solution? (maybe with ddply?)
> 
> ## By the way:
> df1[,"Value"] # works
> df1[,-"Value"] # does not work
> ## Is there a way to exclude columns by names? that would make the code more 
> readable.
> ## I know one could use...
> subset(df1, select=c("Year","Group"))
> ## ... but it seems a bit tedious if you have lots of columns to first remove 
> the 
> ## column name that should be dropped and then put the remaining column names 
> in "select"
> 
> 
> Cheers,
> 
> Marius
> 
> 
> 

__
R-help@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.


[R] Best way/practice to create a new data frame from two given ones with last column computed from the two data frames?

2011-08-18 Thread Marius Hofert
Dear expeRts,

What is the best approach to create a third data frame from two given ones, when
the new/third data frame has last column computed from the last columns of the 
two given
data frames?

## Okay, sounds complicated, so here is an example. Assume we have the two data 
frames:
df1 <- data.frame(Year=rep(2001:2010, each=2), Group=c("Group 1","Group 2"), 
Value=1:20)
df2 <- data.frame(Year=rep(2001:2010, each=2), Group=c("Group 1","Group 2"), 
Value=21:40)

## To make this a bit more fun, let's say the order of elements is different...
(df1 <- df1[sample(1:nrow(df1)),])
(df2 <- df2[sample(1:nrow(df2)),])

## Now I would like to create a third data frame that has "Year" in column one, 
## "Group" in column two, and each entry of column three should consist of the 
## corresponding entry in df1 divided by the one in df2. 

## To achieve this, one could do:
df3 <- df1[with(df1, order(Year,Group)),]
df3$Value <- df3$Value/df2[with(df2, order(Year,Group)),]$Value
colnames(df3)[3] <- "New Value" # typically, the column name changes 

## or one could do:
df3 <- df1[with(df1, order(Year,Group)), -ncol(df1)]
df3 <- cbind(df3, "New Value"=df1[with(df1, 
order(Year,Group)),]$Value/df2[with(df2, order(Year,Group)),]$Value)

## Is there a more elegant solution? (maybe with ddply?)

## By the way:
df1[,"Value"] # works
df1[,-"Value"] # does not work
## Is there a way to exclude columns by names? that would make the code more 
readable.
## I know one could use...
subset(df1, select=c("Year","Group"))
## ... but it seems a bit tedious if you have lots of columns to first remove 
the 
## column name that should be dropped and then put the remaining column names 
in "select"


Cheers,

Marius

__
R-help@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.


Re: [R] How to apply a function to subsets of a data frame *and* obtain a data frame again?

2011-08-17 Thread Marius Hofert
Dear all, 

thanks a lot for the quick help. 
Below is what I built with the hint of Nick.

Cheers,

Marius


library(plyr)

set.seed(1)
(df <- data.frame(Group=rep(c("Group1","Group2","Group3"), each=10), 
Value=c(rexp(10, 1), rexp(10, 4), rexp(10, 
10)))[sample(1:30,30),])
edf <- function(x) ecdf(x)(x) 

ddply(df, .(Group), function(df.) cbind(df., edf=edf(df.$Value))) 


On 2011-08-17, at 13:38 , Hadley Wickham wrote:

>> The following example does what you want using ddply:
>> 
>> library(plyr)
>> edfPerGroup = ddply(df, .(Group), summarise, edf = edf(Value), Value =
>> Value)
> 
> Or slightly more succinctly:
> 
> ddply(df, .(Group), mutate, edf = edf(Value))
> 
> Hadley
> 
> -- 
> Assistant Professor / Dobelman Family Junior Chair
> Department of Statistics / Rice University
> http://had.co.nz/

__
R-help@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.


[R] How to apply a function to subsets of a data frame *and* obtain a data frame again?

2011-08-17 Thread Marius Hofert
Dear all,

First, let's create some data to play around:

set.seed(1)
(df <- data.frame(Group=rep(c("Group1","Group2","Group3"), each=10), 
 Value=c(rexp(10, 1), rexp(10, 4), rexp(10, 
10)))[sample(1:30,30),])

## Now we need the empirical distribution function:
edf <- function(x) ecdf(x)(x) # empirical distribution function evaluated at x

## The big question is how one can apply the empirical distribution function to 
## each subset of df determined by "Group", so how to apply it to Group1, then
## to Group2, and finally to Group3. You might suggest (?) to use tapply:

(edf. <- tapply(df$Value, df$Group, FUN=edf))

## That's correct. But typically, one would like to obtain not only the values, 
## but a data.frame containing the original information and the new 
(edf-)values.
## What's a simple way to get this? (one would be required to first sort df 
## according to Group, then paste the values computed by edf to the sorted df; 
## seems a bit tedious). 
## A solution I have is the following (but I would like to know if there is a 
## simpler one):

(edf.. <- do.call("rbind", lapply(unique(df$Group), function(strg){
subdata <- subset(df, Group==strg) # sub-data
subdata <- cbind(subdata, edf=edf(subdata$Value))
})) )


Cheers,

Marius
__
R-help@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.


Re: [R] lattice: How to vertically adjust an axis label?

2011-07-09 Thread Marius Hofert
Dear David,

thanks for the hint, I completely forgot about phantom(). With that, I can 
solve the problem:

library(lattice)
xyplot(0~0, xlim=c(0,3), scales=list(x=list(at=c(1,1.1),
 labels=c(expression(hat(theta)[italic(n)]),
 
expression(phantom(hat(theta)[italic(n)])*theta*phantom(hat(theta)[italic(n)]))

I use phantom() to put the expression with the largest height to the left of 
the smaller label. Then I also put it on the right side of the smaller label in 
order to center the label again. It's certainly dirty, but it solves the 
problem :-)

Cheers,

Marius

On 2011-07-09, at 24:12 , David Winsemius wrote:

> 
> On Jul 8, 2011, at 6:54 PM, Marius Hofert wrote:
> 
>> Dear expeRts,
>> 
>> How can I vertically adjust an axis tick label so that it is nicely aligned 
>> with
>> the other labels?
>> 
>> library(lattice)
>> xyplot(0~0, xlim=c(0,3), scales=list(x=list(at=c(1,1.1), 
>> labels=c(expression(hat(theta)[italic(n)]),expression(theta)
>> ## aim: move the leftmost expression up so that theta is nicely aligned with 
>> the second
> 
> I don't know how to make a phantom ,  so see if this is any more 
> aesthetically acceptable:
> 
> xyplot(0~0, xlim=c(0,3), scales=list(x=list(at=c(1,1.1),labels=c(
>  expression(atop(phantom(), hat(theta)[italic(n)])),
>   expression(atop(phantom(),theta)) )
>)))
> 
>> theta.
>> 
>> Cheers,
>> 
>> Marius
>> __
>> R-help@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.
> 
> David Winsemius, MD
> West Hartford, CT
> 

__
R-help@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.


[R] lattice: How to vertically adjust an axis label?

2011-07-08 Thread Marius Hofert
Dear expeRts,

How can I vertically adjust an axis tick label so that it is nicely aligned with
the other labels?

library(lattice)
xyplot(0~0, xlim=c(0,3), scales=list(x=list(at=c(1,1.1), 
labels=c(expression(hat(theta)[italic(n)]),expression(theta)
## aim: move the leftmost expression up so that theta is nicely aligned with 
the second theta.

Cheers,

Marius
__
R-help@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.


Re: [R] Odp: data.frame: How to get the classes of all components and how to remove their factor structure?

2011-06-28 Thread Marius Hofert
Dear Petr,

thanks for your posts, they perfectly answered my questions.

Cheers,

Marius


On 2011-06-28, at 09:49 , Petr PIKAL wrote:

>> 
>> Dear expeRts,
>> 
>> I have two questions concerning data frames:
>> (1) How can I apply the class function to each component in a 
> data.frame? 
>> As you can see below, applying class to each column is not the right 
>> approach; applying it to each component seems bulky.
>> (2) After transforming the data frame a bit, the classes of certain 
>> components change to factor. How can I remove the factor structure?
>> 
>> Cheers,
>> 
>> Marius
>> 
>> x <- c(2004:2010, 2002:2011, 2000:2011)
>> df <- data.frame(x=x, group=c(rep("low",7), rep("middle",10), 
> rep("high",12)), 
>> y=x+100*runif(length(x))) 
>> 
>> ## Question (1): why do the following lines do not give the same 
> "class"?
>> apply(df, 2, class)
>> class(df$x)
>> class(df$group)
>> class(df$y)
>> 
>> df. <- as.data.frame(xtabs(y ~ x + group, data=df))
>> 
>> class(df.$x)
>> class(df.$group)
>> class(df.$Freq)
>> 
>> ## Question (2): how can I remove the factor structure from x?
>> df.$x <- as.numeric(as.character(df.$x)) # seems bulky; note that 
> 
> If you do it often you can
> 
> unfactor <- function(x) as.numeric(as.character(x))
> df.$x <- unfactor(df.$x)
> 
> or you can use 
> df. <- as.data.frame(xtabs(y ~ x + group, data=df), 
> stringsAsFactors=FALSE)
> df.$x <- as.numeric(df.$x)
> 
> But it seems to me that it is not much less bulkier.
> 
> Regards
> Petr
> 
> 
>> as.numeric(df.$x) is not correct
>> class(df.$x)
>> __
>> R-help@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.
>

__
R-help@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.


[R] data.frame: How to get the classes of all components and how to remove their factor structure?

2011-06-27 Thread Marius Hofert
Dear expeRts,

I have two questions concerning data frames:
(1) How can I apply the class function to each component in a data.frame? As 
you can see below, applying class to each column is not the right approach; 
applying it to each component seems bulky.
(2) After transforming the data frame a bit, the classes of certain components 
change to factor. How can I remove the factor structure?

Cheers,

Marius

x <- c(2004:2010, 2002:2011, 2000:2011)
df <- data.frame(x=x, group=c(rep("low",7), rep("middle",10), rep("high",12)), 
 y=x+100*runif(length(x))) 

## Question (1): why do the following lines do not give the same "class"?
apply(df, 2, class)
class(df$x)
class(df$group)
class(df$y)

df. <- as.data.frame(xtabs(y ~ x + group, data=df))

class(df.$x)
class(df.$group)
class(df.$Freq)

## Question (2): how can I remove the factor structure from x?
df.$x <- as.numeric(as.character(df.$x)) # seems bulky; note that 
as.numeric(df.$x) is not correct
class(df.$x)
__
R-help@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.


Re: [R] Tricky (?) conversion from data.frame to matrix where not all pairs exist

2011-06-22 Thread Marius Hofert
Hi David,

thanks for the quick response. That's nice. Is there also a way without loading 
an additional package? I'd prefer loading less packages if possible.

Cheers,

Marius


On 2011-06-22, at 15:38 , David Winsemius wrote:

> 
> On Jun 22, 2011, at 9:19 AM, Marius Hofert wrote:
> 
>> Hi,
>> 
>> and what's the simplest way to obtain a *data.frame* with all years?
>> The matching seems more difficult here because the years can/will show up 
>> several times...
>> 
>> (df <- data.frame(year=c(2000, 2001, 2002, 2001, 2000, 2001),
>>block=c("a","a","a","b","c","c"), value=1:6))
>> (df. <- data.frame(year=rep(2000:2002, 3), block=rep(c("a", "b", "c"), 
>> each=3), value=0))
>> # how to fill in the given values?
> 
> These days I think most people would reach for melt() in either reshape or 
> reshape2 packages:
> 
> > require(reshape2)
> Loading required package: reshape2
> > melt(xtb)
>  year block value
> 1 2000 a 1
> 2 2001 a 2
> 3 2002 a 3
> 4 2000 b 0
> 5 2001 b 4
> 6 2002 b 0
> 7 2000 c 5
> 8 2001 c 6
> 9 2002 c 0
> 
> It seems to do a good job of guessing what you want whereas the reshape 
> function in my hands is very failure prone (... yes, the failings are mine.)
> -- 
> David
>> 
>> Cheers,
>> 
>> Marius
>> 
>> 
>> On 2011-06-22, at 14:40 , Dennis Murphy wrote:
>> 
>>> I saw it as an xtabs object - I didn't think to check whether it was
>>> also a matrix object. Thanks for the clarification, David.
>>> 
>>> Dennis
>>> 
>>> On Wed, Jun 22, 2011 at 4:59 AM, David Winsemius  
>>> wrote:
>>>> 
>>>> On Jun 21, 2011, at 6:51 PM, Dennis Murphy wrote:
>>>> 
>>>>> Ahhh...you want a matrix. xtabs() doesn't easily allow coercion to a
>>>>> matrix object, so try this instead:
>>>> 
>>>> What am I missing? A contingency table already inherits from matrix-class
>>>> and if you insisted on coercion it  appears simple:
>>>> 
>>>>> xtb <- xtabs(value ~ year + block, data = df)
>>>>> is.matrix(xtb)
>>>> [1] TRUE
>>>>> as.matrix(xtb)
>>>>block
>>>> year   a b c
>>>> 2000 1 0 5
>>>> 2001 2 4 6
>>>> 2002 3 0 0
>>>> 
>>>> --
>>>> David.
>>>> 
>>>>> 
>>>>> library(reshape)
>>>>> as.matrix(cast(df, year ~ block, fill = 0))
>>>>>  a b c
>>>>> 2000 1 0 5
>>>>> 2001 2 4 6
>>>>> 2002 3 0 0
>>>>> 
>>>>> Hopefully this is more helpful...
>>>>> Dennis
>>>>> 
>>>>> On Tue, Jun 21, 2011 at 3:35 PM, Dennis Murphy  wrote:
>>>>>> 
>>>>>> Hi:
>>>>>> 
>>>>>> xtabs(value ~ year + block, data = df)
>>>>>>   block
>>>>>> year   a b c
>>>>>> 2000 1 0 5
>>>>>> 2001 2 4 6
>>>>>> 2002 3 0 0
>>>>>> 
>>>>>> HTH,
>>>>>> Dennis
>>>>>> 
>>>>>> On Tue, Jun 21, 2011 at 3:13 PM, Marius Hofert  wrote:
>>>>>>> 
>>>>>>> Dear expeRts,
>>>>>>> 
>>>>>>> In the minimal example below, I have a data.frame containing three
>>>>>>> "blocks" of years
>>>>>>> (the years are subsets of 2000 to 2002). For each year and block a
>>>>>>> certain "value" is given.
>>>>>>> I would like to create a matrix that has row names given by all years
>>>>>>> ("2000", "2001", "2002"),
>>>>>>> and column names given by all blocks ("a", "b", "c"); the entries are
>>>>>>> then given by the
>>>>>>> corresponding value or zero if not year-block combination exists.
>>>>>>> 
>>>>>>> What's a short way to achieve this?
>>>>>>> 
>>>>>>> Of course one can setup a matrix and use for loops (see below)... but
>>>>>>> that's not nice.
>>>

Re: [R] Tricky (?) conversion from data.frame to matrix where not all pairs exist

2011-06-22 Thread Marius Hofert
Hi,

and what's the simplest way to obtain a *data.frame* with all years?
The matching seems more difficult here because the years can/will show up 
several times... 

(df <- data.frame(year=c(2000, 2001, 2002, 2001, 2000, 2001), 
 block=c("a","a","a","b","c","c"), value=1:6))
(df. <- data.frame(year=rep(2000:2002, 3), block=rep(c("a", "b", "c"), each=3), 
value=0))
# how to fill in the given values?

Cheers,

Marius


On 2011-06-22, at 14:40 , Dennis Murphy wrote:

> I saw it as an xtabs object - I didn't think to check whether it was
> also a matrix object. Thanks for the clarification, David.
> 
> Dennis
> 
> On Wed, Jun 22, 2011 at 4:59 AM, David Winsemius  
> wrote:
>> 
>> On Jun 21, 2011, at 6:51 PM, Dennis Murphy wrote:
>> 
>>> Ahhh...you want a matrix. xtabs() doesn't easily allow coercion to a
>>> matrix object, so try this instead:
>> 
>> What am I missing? A contingency table already inherits from matrix-class
>> and if you insisted on coercion it  appears simple:
>> 
>>> xtb <- xtabs(value ~ year + block, data = df)
>>> is.matrix(xtb)
>> [1] TRUE
>>> as.matrix(xtb)
>>  block
>> year   a b c
>>  2000 1 0 5
>>  2001 2 4 6
>>  2002 3 0 0
>> 
>> --
>> David.
>> 
>>> 
>>> library(reshape)
>>> as.matrix(cast(df, year ~ block, fill = 0))
>>>a b c
>>> 2000 1 0 5
>>> 2001 2 4 6
>>> 2002 3 0 0
>>> 
>>> Hopefully this is more helpful...
>>> Dennis
>>> 
>>> On Tue, Jun 21, 2011 at 3:35 PM, Dennis Murphy  wrote:
>>>> 
>>>> Hi:
>>>> 
>>>> xtabs(value ~ year + block, data = df)
>>>> block
>>>> year   a b c
>>>>  2000 1 0 5
>>>>  2001 2 4 6
>>>>  2002 3 0 0
>>>> 
>>>> HTH,
>>>> Dennis
>>>> 
>>>> On Tue, Jun 21, 2011 at 3:13 PM, Marius Hofert  wrote:
>>>>> 
>>>>> Dear expeRts,
>>>>> 
>>>>> In the minimal example below, I have a data.frame containing three
>>>>> "blocks" of years
>>>>> (the years are subsets of 2000 to 2002). For each year and block a
>>>>> certain "value" is given.
>>>>> I would like to create a matrix that has row names given by all years
>>>>> ("2000", "2001", "2002"),
>>>>> and column names given by all blocks ("a", "b", "c"); the entries are
>>>>> then given by the
>>>>> corresponding value or zero if not year-block combination exists.
>>>>> 
>>>>> What's a short way to achieve this?
>>>>> 
>>>>> Of course one can setup a matrix and use for loops (see below)... but
>>>>> that's not nice.
>>>>> The problem is that the years are not running from 2000 to 2002 for all
>>>>> three "blocks"
>>>>> (the second block only has year 2001, the third one has only 2000 and
>>>>> 2001).
>>>>> In principle, table() nicely solves such a problem (see below) and fills
>>>>> in zeros.
>>>>> This is what I would like in the end, but all non-zero entries should be
>>>>> given by df$value,
>>>>> not (as table() does) by their counts.
>>>>> 
>>>>> Cheers,
>>>>> 
>>>>> Marius
>>>>> 
>>>>> (df <- data.frame(year=c(2000, 2001, 2002, 2001, 2000, 2001),
>>>>> block=c("a","a","a","b","c","c"), value=1:6))
>>>>> table(df[,1:2]) # complements the years and fills in 0
>>>>> 
>>>>> year <- c(2000, 2001, 2002)
>>>>> block <- c("a", "b", "c")
>>>>> res <- matrix(0, nrow=3, ncol=3, dimnames=list(year, block))
>>>>> for(i in 1:3){ # year
>>>>>   for(j in 1:3){ # block
>>>>>   for(k in 1:nrow(df)){
>>>>>   if(df[k,"year"]==year[i] && df[k,"block"]==block[j]) res[i,j]
>>>>> <- df[k,"value"]
>>>>>   }
>>>>>   }
>>>>> }
>>>>> res # does the job; but seems complicated
>>> 
>> 
>> 
>> David Winsemius, MD
>> West Hartford, CT
>> 
>> 

__
R-help@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.


Re: [R] Tricky (?) conversion from data.frame to matrix where not all pairs exist

2011-06-21 Thread Marius Hofert
Thanks a lot! Works like charm :-)))

Cheers,

Marius

On 2011-06-22, at 24:51 , Dennis Murphy wrote:

> Ahhh...you want a matrix. xtabs() doesn't easily allow coercion to a
> matrix object, so try this instead:
> 
> library(reshape)
> as.matrix(cast(df, year ~ block, fill = 0))
> a b c
> 2000 1 0 5
> 2001 2 4 6
> 2002 3 0 0
> 
> Hopefully this is more helpful...
> Dennis
> 
> On Tue, Jun 21, 2011 at 3:35 PM, Dennis Murphy  wrote:
>> Hi:
>> 
>> xtabs(value ~ year + block, data = df)
>>  block
>> year   a b c
>>  2000 1 0 5
>>  2001 2 4 6
>>  2002 3 0 0
>> 
>> HTH,
>> Dennis
>> 
>> On Tue, Jun 21, 2011 at 3:13 PM, Marius Hofert  wrote:
>>> Dear expeRts,
>>> 
>>> In the minimal example below, I have a data.frame containing three "blocks" 
>>> of years
>>> (the years are subsets of 2000 to 2002). For each year and block a certain 
>>> "value" is given.
>>> I would like to create a matrix that has row names given by all years 
>>> ("2000", "2001", "2002"),
>>> and column names given by all blocks ("a", "b", "c"); the entries are then 
>>> given by the
>>> corresponding value or zero if not year-block combination exists.
>>> 
>>> What's a short way to achieve this?
>>> 
>>> Of course one can setup a matrix and use for loops (see below)... but 
>>> that's not nice.
>>> The problem is that the years are not running from 2000 to 2002 for all 
>>> three "blocks"
>>> (the second block only has year 2001, the third one has only 2000 and 2001).
>>> In principle, table() nicely solves such a problem (see below) and fills in 
>>> zeros.
>>> This is what I would like in the end, but all non-zero entries should be 
>>> given by df$value,
>>> not (as table() does) by their counts.
>>> 
>>> Cheers,
>>> 
>>> Marius
>>> 
>>> (df <- data.frame(year=c(2000, 2001, 2002, 2001, 2000, 2001),
>>>  block=c("a","a","a","b","c","c"), value=1:6))
>>> table(df[,1:2]) # complements the years and fills in 0
>>> 
>>> year <- c(2000, 2001, 2002)
>>> block <- c("a", "b", "c")
>>> res <- matrix(0, nrow=3, ncol=3, dimnames=list(year, block))
>>> for(i in 1:3){ # year
>>>for(j in 1:3){ # block
>>>for(k in 1:nrow(df)){
>>>if(df[k,"year"]==year[i] && df[k,"block"]==block[j]) res[i,j] <- 
>>> df[k,"value"]
>>>}
>>>}
>>> }
>>> res # does the job; but seems complicated
>>> 
>>> __
>>> R-help@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.
>>> 
>> 

__
R-help@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.


[R] Tricky (?) conversion from data.frame to matrix where not all pairs exist

2011-06-21 Thread Marius Hofert
Dear expeRts,

In the minimal example below, I have a data.frame containing three "blocks" of 
years 
(the years are subsets of 2000 to 2002). For each year and block a certain 
"value" is given.
I would like to create a matrix that has row names given by all years ("2000", 
"2001", "2002"), 
and column names given by all blocks ("a", "b", "c"); the entries are then 
given by the 
corresponding value or zero if not year-block combination exists. 

What's a short way to achieve this? 

Of course one can setup a matrix and use for loops (see below)... but that's 
not nice.
The problem is that the years are not running from 2000 to 2002 for all three 
"blocks" 
(the second block only has year 2001, the third one has only 2000 and 2001). 
In principle, table() nicely solves such a problem (see below) and fills in 
zeros. 
This is what I would like in the end, but all non-zero entries should be given 
by df$value, 
not (as table() does) by their counts. 

Cheers,

Marius

(df <- data.frame(year=c(2000, 2001, 2002, 2001, 2000, 2001), 
  block=c("a","a","a","b","c","c"), value=1:6))
table(df[,1:2]) # complements the years and fills in 0 

year <- c(2000, 2001, 2002)
block <- c("a", "b", "c")
res <- matrix(0, nrow=3, ncol=3, dimnames=list(year, block))
for(i in 1:3){ # year 
for(j in 1:3){ # block 
for(k in 1:nrow(df)){
if(df[k,"year"]==year[i] && df[k,"block"]==block[j]) res[i,j] <- 
df[k,"value"]
}
}
}
res # does the job; but seems complicated

__
R-help@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.


Re: [R] plot + axis: Individually moving tick labels with hadj?

2011-06-03 Thread Marius Hofert
Hi Sarah,

very nice, thanks!

Cheers,

Marius

On 2011-06-03, at 13:14 , Sarah Goslee wrote:

> Hi Marius,
> 
> I actually prefer the first (default) arrangement, with the labels centered, 
> but
> if you want to align the equals under the tick mark one option is to use
> axis() twice:
> 
> plot(1:5, 5:1, xaxt="n")
> axis(1, at=1:5, labels=c(1,2,"",4,5))
> axis(1, at=3.15, tick=FALSE, labels=expression(3==beta[foo]))
> 
> Sarah
> 
> On Fri, Jun 3, 2011 at 7:02 AM, Marius Hofert  wrote:
>> Dear all,
>> 
>> consider the following plot:
>> 
>> plot(1:5, 5:1, xaxt="n")
>> axis(1, at=1:5, labels=c(1,2,expression(3==beta[foo]),4,5))
>> 
>> the label at 3 is not nice, so consider this
>> plot(1:5, 5:1, xaxt="n")
>> axis(1, at=1:5, labels=c(1,2,expression(3==beta[foo]),4,5),
>> padj=c(0,0,0.18,0,0))
>> 
>> Now I tried to move the label horizontally so that the equality sign is
>> vertically aligned with the tick. Since hadj moves all labels, I tried:
>> plot(1:5, 5:1, xaxt="n")
>> axis(1, at=1:5, labels=c(1,2,expression(3==beta[foo]),4,5),
>> hadj=c(0,0,0.22,0,0), padj=c(0,0,0.18,0,0))
>> 
>> Why is it not possible to individually move the labels horizontally?
>> Simply moving all of them does not look very good...
>> plot(1:5, 5:1, xaxt="n")
>> axis(1, at=1:5, labels=c(1,2,expression(3==beta[foo]),4,5),
>> hadj=0.22, padj=c(0,0,0.18,0,0))
>> 
>> Cheers,
>> 
>> Marius
>> 
> 
> 
> -- 
> Sarah Goslee
> http://www.functionaldiversity.org

__
R-help@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.


[R] plot + axis: Individually moving tick labels with hadj?

2011-06-03 Thread Marius Hofert
Dear all,

consider the following plot:

plot(1:5, 5:1, xaxt="n") 
axis(1, at=1:5, labels=c(1,2,expression(3==beta[foo]),4,5))

the label at 3 is not nice, so consider this
plot(1:5, 5:1, xaxt="n") 
axis(1, at=1:5, labels=c(1,2,expression(3==beta[foo]),4,5),
 padj=c(0,0,0.18,0,0)) 

Now I tried to move the label horizontally so that the equality sign is 
vertically aligned with the tick. Since hadj moves all labels, I tried:
plot(1:5, 5:1, xaxt="n") 
axis(1, at=1:5, labels=c(1,2,expression(3==beta[foo]),4,5),
 hadj=c(0,0,0.22,0,0), padj=c(0,0,0.18,0,0))

Why is it not possible to individually move the labels horizontally?
Simply moving all of them does not look very good...
plot(1:5, 5:1, xaxt="n") 
axis(1, at=1:5, labels=c(1,2,expression(3==beta[foo]),4,5),
 hadj=0.22, padj=c(0,0,0.18,0,0))

Cheers,

Marius

__
R-help@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.


Re: [R] lattice + plotmath: how to get a variable in bold face?

2011-06-02 Thread Marius Hofert
Dear Dennis, Dear Peter,

thank you very much, as.character() worked perfectly. Nice solution :-)

All the best,

Marius

On 2011-06-03, at 03:42 , Dennis Murphy wrote:

> If you're trying to figure out a way to embolden a Greek letter in
> plotmath, it ain't gonna happen. From the plotmath help page:
> 
> "Note that bold, italic and bolditalic do not apply to symbols, and
> hence not to the Greek symbols such as mu which are displayed in the
> symbol font. They also do not apply to numeric constants."
> 
> That's why Peter suggested using as.character(N), where N is a number.
> That trick obviously won't work for symbols, as noted above.
> 
> Dennis
> 
> On Thu, Jun 2, 2011 at 3:50 PM, Marius Hofert  wrote:
>> Dear all,
>> 
>> How can I get a bold "1000" in the title? I would like to use a variable (as 
>> opposed to putting in "1000" directly).
>> 
>> library(lattice)
>> N <- 1000
>> xyplot(0~0, xlab.top=list(label=as.expression(bquote(bold("foo" ~ .(N) ~ 
>> "bar"))), font=2, cex=1.2))
>> ## => "font=2" is ignored (of course)
>> 
>> Cheers,
>> 
>> Marius
>> __
>> R-help@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.
>> 

__
R-help@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.


[R] lattice + plotmath: how to get a variable in bold face?

2011-06-02 Thread Marius Hofert
Dear all,

How can I get a bold "1000" in the title? I would like to use a variable (as 
opposed to putting in "1000" directly).

library(lattice)
N <- 1000
xyplot(0~0, xlab.top=list(label=as.expression(bquote(bold("foo" ~ .(N) ~ 
"bar"))), font=2, cex=1.2)) 
## => "font=2" is ignored (of course)

Cheers,

Marius
__
R-help@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.


Re: [R] plotmath: paste string and expression [from a vector of expressions]

2011-06-02 Thread Marius Hofert
Dear Dennis, Dear Uwe, Dear David,

many thanks for helping. Dennis and David, your solutions seemed perfectly 
fine, but when I applied it to my original problem, it did not show a title. 
Below is a (longer) minimal example (the first part is from the help page of 
bbmle). Is this a bug in bbmle? Hmmm...

library(bbmle)

x <- 0:10
y <- c(26, 17, 13, 12, 20, 5, 9, 8, 5, 4, 8)
d <- data.frame(x,y)

## in general it is best practice to use the `data' argument,
##  but variables can also be drawn from the global environment
LL <- function(ymax=15, xhalf=6)
-sum(stats::dpois(y, lambda=ymax/(1+x/xhalf), log=TRUE))

## uses default parameters of LL
(fit <- mle2(LL))
ml <- mle2(LL, fixed=list(xhalf=6))
mlp <- profile(ml)
 
vars <- c(quote(theta), quote(beta))
plot(mlp, main=bquote(bold("Foo"~.(vars[[2]]

Cheers,

Marius

On 2011-06-02, at 22:23 , Dennis Murphy wrote:

> Hi:
> 
> This seems to work:
> 
> vars2 <- c(quote(alpha), quote(beta))   # returns a list of mode call
> plot(0, 0, main = bquote(bold('Foo '~.(vars2[[2]]
> 
> Expressions are only evaluated once, which means that inner
> expressions are not evaluated. You need a call object rather than an
> expression inside of bquote().
> 
> HTH,
> Dennis
> 
> On Thu, Jun 2, 2011 at 11:43 AM, Marius Hofert  wrote:
>> Dear all,
>> 
>> I have a vector of expressions and would like to "paste" some string to it 
>> before using it in a plot:
>> 
>> vars <- vector("expression", 2)
>> vars[1] <- expression(alpha)
>> vars[2] <- expression(beta)
>> plot(0, 0, main=substitute(bold("Foo" ~~ VAR), list(VAR=vars[2]) ))
>> 
>> Although I tried hard, I just can't figure out how to solve this. The title 
>> should be "Foo ", where  is the greek letter. I tried some 
>> constructions with bquote but that wasn't successful... I also looked in the 
>> mailing list but couldn't find anything helpful [I am sure I overlooked 
>> something].
>> 
>> Cheers,
>> 
>> Marius
>> 
>> __
>> R-help@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.
>> 

__
R-help@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.


Re: [R] plotmath: paste string and expression [from a vector of expressions]

2011-06-02 Thread Marius Hofert
Dear Uwe,

thanks for your help. Actually, I first thought about writing your solution in 
the email in order to make clear that it is not the solution I'm looking for 
:-) My goal is to work with the vector "vars" of expressions. The example is 
only a minimal example and for that your solution is perfectly fine, but my 
original problem is more complicated and there it makes sense to work with a 
vector of expressions. Do you know a solution to that? I tried many things... 
the obvious plot(0, 0, main=substitute(bold("Foo" ~~ VAR), list(VAR=vars[2]) )) 
did not work...

Cheers,

Marius

On 2011-06-02, at 22:14 , Uwe Ligges wrote:

> 
> 
> On 02.06.2011 20:43, Marius Hofert wrote:
>> Dear all,
>> 
>> I have a vector of expressions and would like to "paste" some string to it 
>> before using it in a plot:
>> 
>> vars<- vector("expression", 2)
>> vars[1]<- expression(alpha)
>> vars[2]<- expression(beta)
>> plot(0, 0, main=substitute(bold("Foo" ~~ VAR), list(VAR=vars[2]) ))
>> 
>> Although I tried hard, I just can't figure out how to solve this. The title 
>> should be "Foo", where  is the greek letter. I tried some 
>> constructions with bquote but that wasn't successful... I also looked in the 
>> mailing list but couldn't find anything helpful [I am sure I overlooked 
>> something].
> 
> 
> plot(0, 0, main=expression("Foo" ~~ theta))
> 
> Uwe Ligges
> 
> 
> 
>> Cheers,
>> 
>> Marius
>> 
>> __
>> R-help@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.

__
R-help@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.


[R] plotmath: paste string and expression [from a vector of expressions]

2011-06-02 Thread Marius Hofert
Dear all,

I have a vector of expressions and would like to "paste" some string to it 
before using it in a plot:

vars <- vector("expression", 2)
vars[1] <- expression(alpha)
vars[2] <- expression(beta)
plot(0, 0, main=substitute(bold("Foo" ~~ VAR), list(VAR=vars[2]) ))

Although I tried hard, I just can't figure out how to solve this. The title 
should be "Foo ", where  is the greek letter. I tried some 
constructions with bquote but that wasn't successful... I also looked in the 
mailing list but couldn't find anything helpful [I am sure I overlooked 
something].

Cheers,

Marius

__
R-help@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.


[R] ftable: how to replace NA and format entries without changing their mode?

2011-05-28 Thread Marius Hofert
Dear all,

another ftable problem, now related to formatC.
One typically would like to format entries in an ftable (adjust digits, replace 
NA, ...)
before format() is applied to convert the formatted ftable to an object which 
xtable can deal with. The output of xtable can then be used within a LaTeX 
table.

The problem I face is that the ftable entries [numeric] change their mode when 
one of the operations "adjust digits" or "replace NA" is applied. Here is a 
minimal example:

## first adjusting the format, then trying to remove NA
(ft <- ftable(Titanic)) # ftable
ft[1,1] <- NA # create an NA entry to show the behavior
is.numeric(ft) # => is numeric
ft. <- formatC(ft, digits=1, format="f") # adjust format 
is.numeric(ft.) # => not numeric anymore => one can not further use is.na() etc.
ft.[is.na(ft.)] <- "my.Command.To.Deal.With.NA" # does not work because is.na() 
does not find NA
ft. # (of course) still contains NA

## first remove NA, then trying to adjust the format
(ft <- ftable(Titanic)) # ftable
ft[1,1] <- NA
ft[is.na(ft)] <- "my.LaTeX.Code.To.Deal.With.NA"
is.character(ft) # => now character, adjusting the format of the numbers with 
formatC not possible anymore
ft 
formatC(ft, digits=1, format="f") # (of course) not working anymore

How can I accomplish both (example-)tasks without changing the mode
of the ftable entries? 
Note: I would like to keep the ftable structure since this nicely converts to a
LaTeX table later on. 

Cheers,

Marius

__
R-help@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.


  1   2   3   >