Re: [R] Converting chr to num

2018-08-20 Thread Spencer Graves
  Have you considered "Ecfun::asNumericChar" (and 
"Ecfun::asNumericDF")?



DF <- data.frame(variable = c("12.6% ", "30.9%", "61.4%", "1"))
Ecfun::asNumericChar(DF$variable)
[1] 0.126 0.309 0.614 1.000


  If you read the documentation including the examples, you will 
see that many of these issues and others are handled automatically in 
the way that I thought was the most sensible.  If you disagree, we can 
discuss other examples and perhaps modify the code for those functions.



  Spencer Graves


On 2018-08-20 00:26, Rui Barradas wrote:

Hello,

Inline.

On 20/08/2018 01:08, Daniel Nordlund wrote:

See comment inline below:

On 8/18/2018 10:06 PM, Rui Barradas wrote:

Hello,

It also works with class "factor":

df <- data.frame(variable = c("12.6%", "30.9%", "61.4%"))
class(df$variable)
#[1] "factor"

as.numeric(gsub(pattern = "%", "", df$variable))
#[1] 12.6 30.9 61.4


This is because sub() and gsub() return a character vector and the 
instruction becomes an equivalent of what the help page ?factor 
documents in section Warning:


To transform a factor f to approximately its original numeric 
values, as.numeric(levels(f))[f] is recommended and slightly more 
efficient than as.numeric(as.character(f)).



Also, I would still prefer

as.numeric(sub(pattern = "%$","",df$variable))
#[1] 12.6 30.9 61.4

The pattern is more strict and there is no need to search&replace 
multiple occurrences of '%'.


The pattern is more strict, and that could cause the conversion to 
fail if the process that created the strings resulted in trailing 
spaces. 


That's true, and I had thought of that but it wasn't in the OP's 
problem description.

The '$' could still be used with something like "%\\s*$":

as.numeric(sub('%\\s*$', '', df$variable))
#[1] 12.6 30.9 61.4


Rui Barradas



Without the '$' the conversion succeeds.

df <- data.frame(variable = c("12.6% ", "30.9%", "61.4%"))
as.numeric(sub('%$', '', df$variable))
[1]   NA 30.9 61.4
Warning message:
NAs introduced by coercion


<<>>


Dan



---
This email has been checked for viruses by AVG.
https://www.avg.com

__
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] Using rmarkdown with many plots created in a loop

2018-08-20 Thread Thierry Onkelinx
Dear Don,

Have a look at the knit_expand() function. Then you can create two Rmd
files. One main file and one template file for the subsets. knit_expand()
will find and replace anything between double curly brackets ("{{x}}" in
the example below) with the value of the variable.

The main file:

---
title: "main"
output: html_document
---

```{r setup, include=FALSE}
library(knitr)
```

```{r}
mydf <- data.frame(
  id = 1:4,
  x = rnorm(100),
  y = rnorm(100)
)
```

```{r}
rmd <- sapply(
  1:4,
  function(x) {
knit_expand("child.Rmd", x = x)
  }
)
rmd <- paste(rmd, collapse = "\n")
cat(rmd)
```
```{r results = "asis"}
rendered <- knit(text = rmd, quiet = TRUE)
cat(rendered, sep = "\n")
```


The child.Rmd file

## ID {{x}}

```{r, fig.cap = "The caption: ID = {{x}}", echo = FALSE}
i <- {{x}}
detail <- subset(mydf, id == i)
plot(x ~ y, data = detail)
```

Best regards,


ir. Thierry Onkelinx
Statisticus / Statistician

Vlaamse Overheid / Government of Flanders
INSTITUUT VOOR NATUUR- EN BOSONDERZOEK / RESEARCH INSTITUTE FOR NATURE AND
FOREST
Team Biometrie & Kwaliteitszorg / Team Biometrics & Quality Assurance
thierry.onkel...@inbo.be
Havenlaan 88 bus 73, 1000 Brussel
www.inbo.be

///
To call in the statistician after the experiment is done may be no more
than asking him to perform a post-mortem examination: he may be able to say
what the experiment died of. ~ Sir Ronald Aylmer Fisher
The plural of anecdote is not data. ~ Roger Brinner
The combination of some data and an aching desire for an answer does not
ensure that a reasonable answer can be extracted from a given body of data.
~ John Tukey
///



2018-08-17 1:44 GMT+02:00 MacQueen, Don via R-help :

> I would appreciate some suggestions of a good way to prepare a report
> using rmarkdown,
> in which I loop through subsets of a data set, creating a plot of each
> subset, and interspersing
> among the figures some text relevant to each figure.
>
> One way is to have an R script write the rmd file, then render it.
> It works, but it's cumbersome and difficult to get the rmd syntax correct.
> I would very much appreciate suggestions for a better way.
>
> Reproducible example below.
>
> Thanks
> -Don
>
>
> Example data (other data structures could be used), and an example using
> this approach.
>
> myd <- lapply( 1:3,
>   function(i) list(df=data.frame(x=1:5, y=rnorm(5)),
>comment=paste('Data', LETTERS[i]))
>   )
>
> Example interactive review (details would change depending on data
> structure)
> (I would typically insert pauses when working interactively)
>
> for (i in 1:3) {
>   cat(paste('Figure',i,'shows',myd[[i]]$comment),'\n')
>   with(myd[[i]]$df , plot(x,y))
>   mtext(myd[[i]]$comment)
>   mtext( paste(nrow(myd[[i]]$df),'points'), adj=1)
> }
>
> Note that along with the data I've saved some comments relevant to each
> subset.
> I've calculated them in the example data, but in general they could be
> completely
> arbitrary and come from anywhere.
>
> Now I'd like to get the same plots and comments into a report prepared
> using rmarkdown.
> Here's one way, having the loop create an rmd file, then rendering it.
>
> ### example script begins
> library(rmarkdown)
>
> myf <- 'myd.rmd'
> sink(myf)
> cat('---
> title: Example
> ---
>
> Here are some figures with a comment appearing before each.\n\n'
> )
> sink()
>
> for (i in 1:3) {
>   cat(paste('Figure',i,'comment:',myd[[i]]$comment),'\n', file=myf,
> append=TRUE)
>
>   cat("
> ```{r  echo=FALSE, fig.cap='",paste('fig',i),"caption.'}
>   with(myd[[",i,"]]$df , plot(x,y))
>   mtext(myd[[",i,"]]$comment)
>   mtext( paste(nrow(myd[[",i,"]]$df),'points'), adj=1)
> ```
> ", file=myf, append=TRUE)
>
> }
>
> cat('Done with report\n', file=myf, append=TRUE)
>
> render(myf)
>
> --
> Don MacQueen
> Lawrence Livermore National Laboratory
> 7000 East Ave., L-627
> Livermore, CA 94550
> 925-423-1062
> Lab cell 925-724-7509
>
>
>
> __
> 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.
>

[[alternative HTML version deleted]]

__
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] Using rmarkdown with many plots created in a loop

2018-08-20 Thread Richard M. Heiberger
## Don,

## This is how I would approach the task of a set of coordinated plots.
## I would place individual plots inside a table.  The rows would index the
## datasets and there would be one or more data or description columns
## in addition to the column containing the graphs.

## I use the microplot package that I placed on CRAN about two years ago.

## install.packages("microplot") ## if necessary


library(microplot)
latexSetOptions()

## I normally use lattice.  microplot also works with ggplot or base graphics
library(lattice)

## I placed your data into a single data.frame
myd <- lapply( 1:3,
  function(i) list(df=data.frame(x=1:5, y=rnorm(5)),
   comment=paste('Data', LETTERS[i]))
  )

mydf <- cbind(group=rep(c("A", "B", "C"), each=5),
  rbind(myd[[1]]$df, myd[[2]]$df, myd[[3]]$df))
mydf


## construct a lattice with multiple panels
my.lattice <-
  xyplot(y ~ x | group, data=mydf,
 layout=c(1,3), as.table=TRUE, col="black",
 scales=list(alternating=FALSE),
 ylab=list(rot=1))
my.lattice


## microplot provides latex.trellis, which is a method for Hmisc::latex

## simplest display
latex(my.lattice)

## now with comments and optional additional arguments
mycomments <-
  c("Interesting Comment",
"Full \\LaTeX\\ with an equation $e^{-x^2}$",
"\\begin{tabular}{l}$\\frac{dy}{dx}$ is interesting and
has multiple lines\\end{tabular}")

latex(my.lattice,
  title="Dataset",
  height.panel=1, width.panel=1.5, ## inches
  height.x.axis=.38, width.y.axis=.45,
  graph.header="xyplot(y ~ x | group)",
  dataobject=mycomments,
  colheads=c("Comments", "", "", "xyplot( y \\~{} x )"),
  caption="Very Interesting Caption",
  caption.loc="bottom",
  arraystretch=1.5)

## microplot produces MS Word tables as well as LaTeX tables.
## microplot works with  ‘Sweave’, ‘knitr’, ‘emacs’ ‘orgmode’, and ‘rmarkdown’

## Start with ?microplot-package
## and look at the demos and examples and vignette.

## Rich

On Thu, Aug 16, 2018 at 7:44 PM, MacQueen, Don via R-help
 wrote:
> I would appreciate some suggestions of a good way to prepare a report using 
> rmarkdown,
> in which I loop through subsets of a data set, creating a plot of each 
> subset, and interspersing
> among the figures some text relevant to each figure.
>
> One way is to have an R script write the rmd file, then render it.
> It works, but it's cumbersome and difficult to get the rmd syntax correct.
> I would very much appreciate suggestions for a better way.
>
> Reproducible example below.
>
> Thanks
> -Don
>
>
> Example data (other data structures could be used), and an example using this 
> approach.
>
> myd <- lapply( 1:3,
>   function(i) list(df=data.frame(x=1:5, y=rnorm(5)),
>comment=paste('Data', LETTERS[i]))
>   )
>
> Example interactive review (details would change depending on data structure)
> (I would typically insert pauses when working interactively)
>
> for (i in 1:3) {
>   cat(paste('Figure',i,'shows',myd[[i]]$comment),'\n')
>   with(myd[[i]]$df , plot(x,y))
>   mtext(myd[[i]]$comment)
>   mtext( paste(nrow(myd[[i]]$df),'points'), adj=1)
> }
>
> Note that along with the data I've saved some comments relevant to each 
> subset.
> I've calculated them in the example data, but in general they could be 
> completely
> arbitrary and come from anywhere.
>
> Now I'd like to get the same plots and comments into a report prepared using 
> rmarkdown.
> Here's one way, having the loop create an rmd file, then rendering it.
>
> ### example script begins
> library(rmarkdown)
>
> myf <- 'myd.rmd'
> sink(myf)
> cat('---
> title: Example
> ---
>
> Here are some figures with a comment appearing before each.\n\n'
> )
> sink()
>
> for (i in 1:3) {
>   cat(paste('Figure',i,'comment:',myd[[i]]$comment),'\n', file=myf, 
> append=TRUE)
>
>   cat("
> ```{r  echo=FALSE, fig.cap='",paste('fig',i),"caption.'}
>   with(myd[[",i,"]]$df , plot(x,y))
>   mtext(myd[[",i,"]]$comment)
>   mtext( paste(nrow(myd[[",i,"]]$df),'points'), adj=1)
> ```
> ", file=myf, append=TRUE)
>
> }
>
> cat('Done with report\n', file=myf, append=TRUE)
>
> render(myf)
>
> --
> Don MacQueen
> Lawrence Livermore National Laboratory
> 7000 East Ave., L-627
> Livermore, CA 94550
> 925-423-1062
> Lab cell 925-724-7509
>
>
>
> __
> 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, repro

[R] Transforming data for nice output table

2018-08-20 Thread David Doyle
Hello everyone,

I'm trying to generate tables of my data out of R for my report.

My data is setup in the format as follows and the example can be found at:
http://doylesdartden.com/R/ExampleData.csv

LocationDateYear  GW_Elevation
127(I)5/14/2006 2006   752.46
119(I)5/14/2006 2006   774.67
127(I)6/11/2007 2007   752.06
119(I)6/11/2007 2007   775.57

I would like to generate a table that showed

LocationGW_Elevation 2006GW_Elevation 2007GW_Elevation xxx.

119(I)774.67  775.57
  
127(I)752.46  752.06
  
  XX   XX

 Any thoughts on how to transform the data so it would be in this format??

Thank you for your time

David Doyle

[[alternative HTML version deleted]]

__
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] download.file() problems with binary files containing EOF byte in Windows

2018-08-20 Thread Scott Sherrill-Mix
Hello,
I'm trying to get a package to pass win-builder and have been having a
bit of trouble with Windows R and binary files (in my case a small
.tar.gz used in testing). After a little debugging, I think I've
narrowed it down to download.file() truncating files to the first '1a'
byte (often used for EOF but I think a valid byte inside gzip files)
on downloads from local "file://xxx". I'm trying to figure out if this
is a known "feature" of Windows that I should just avoid or does this
seem like a bug?

For example:

#write a file starting with byte 1a (decimal 26)
writeBin(26:100,'tmp.bin',size=1)
download.file('file://tmp.bin','download.bin')
file.size('tmp.bin')
file.size('download.bin')

On Windows (session info below), I get file sizes of 75 and 0 and on
Linux I get 75 and 75.

As a more real world example, if I download.file() on a .gz file then
a remote download seems to return different size files from a local
download. For example for a gz file from a google hit about gzip
(http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art053):

download.file('http://commandlinefanatic.com/gunzip.c.gz','gunzip.c.gz')
download.file('file://gunzip.c.gz','dl.gz')
file.size('gunzip.c.gz')
file.size('dl.gz')

I get a 4704 byte file for the remote download and 360 for the local
download in Windows (versus 4704 and 4704 on Linux). Note that the
361st byte is 1a:

readBin('gunzip.c.gz','raw',361)

The various download.file options don't seem to fix this with the same 360 bytes
for:

download.file('file://gunzip.c.gz','dl.gz',mode='wb')
file.size('dl.gz')
download.file('file://gunzip.c.gz','dl.gz',mode='wb',method='internal')
file.size('dl.gz')

It looks like the 'auto' and 'internal' methods both resolve to the
'wininet' method on Windows and mode is automatically set to 'wb' for
gz files so maybe not surprising those don't change things.

Thanks,
Scott

## Windows sessionInfo():
R version 3.5.1 (2018-07-02)

Platform: x86_64-w64-mingw32/x64 (64-bit)

Running under: Windows 8.1 x64 (build 9600)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252


attached base packages:

[1] stats graphics  grDevices utils datasets  methods   base


loaded via a namespace (and not attached):

[1] compiler_3.5.1


## Linux sessionInfo():
R version 3.4.4 (2018-03-15)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.5 LTS

Matrix products: default
BLAS: /usr/lib/libblas/libblas.so.3.6.0
LAPACK: /usr/lib/lapack/liblapack.so.3.6.0

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.4.4

__
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] Transforming data for nice output table

2018-08-20 Thread Rui Barradas

Hello,

This is a very frequent question.
I could rewrite one or two answers taken from StackOverflow:

https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format


But there you will have more options.


Hope this helps,

Rui Barradas

On 20/08/2018 20:17, David Doyle wrote:

Hello everyone,

I'm trying to generate tables of my data out of R for my report.

My data is setup in the format as follows and the example can be found at:
http://doylesdartden.com/R/ExampleData.csv

LocationDateYear  GW_Elevation
127(I)5/14/2006 2006   752.46
119(I)5/14/2006 2006   774.67
127(I)6/11/2007 2007   752.06
119(I)6/11/2007 2007   775.57

I would like to generate a table that showed

LocationGW_Elevation 2006GW_Elevation 2007GW_Elevation xxx.

119(I)774.67  775.57
   
127(I)752.46  752.06
   
  XX   XX

  Any thoughts on how to transform the data so it would be in this format??

Thank you for your time

David Doyle

[[alternative HTML version deleted]]

__
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.



---
This email has been checked for viruses by AVG.
https://www.avg.com

__
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] plotmath and logical operators?

2018-08-20 Thread MacQueen, Don via R-help
I would like to use plotmath to annotate a plot with an expression that 
includes a logical operator.

## works well
tmp <- expression(x >= 3)
plot(1)
mtext(tmp)

## not so well
tmp <- expression(x >= 3 &  y <= 3)
plot(1)
mtext(tmp)

Although the text that's displayed makes sense, it won't be obvious to my 
non-mathematical audience.

I'd appreciate suggestions.


I've found a work-around that gets the annotation to look right
  tmpw <- expression(paste( x >= 3, " & ", y <= 3) )
  plot(1)
  mtext(tmpw)


But it breaks my original purpose, illustrated by this example:

df <- data.frame(x=1:5, y=1:5)
tmp <- expression(x >= 3 & y <= 3)
tmpw <- expression(paste( x >= 3, " & ", y <= 3) )
with(df, eval(tmp))
[1] FALSE FALSE  TRUE FALSE FALSE
with(df, eval(tmpw))
[1] "FALSE  &  TRUE" "FALSE  &  TRUE" "TRUE  &  TRUE"  "TRUE  &  FALSE" "TRUE  
&  FALSE"

Thanks
-Don

--
Don MacQueen
Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062
Lab cell 925-724-7509
 
 

__
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] Request for R Assistance: Downloading Data

2018-08-20 Thread Spencer Brackett
 Please ignore my last post/inquiry... I have solved the problem. Thanks
again for the help!

On Sun, Aug 19, 2018 at 5:43 PM Sparks, John  wrote:

> I agree with Jeff.  The data type is the problem.  I wrote what I wrote
> without looking at the problem very carefully.
>
>
> --JJS
>
>
> --
> *From:* Jeff Newmiller 
> *Sent:* Sunday, August 19, 2018 4:38 PM
> *To:* r-help@r-project.org; Sparks, John; Spencer Brackett;
> r-help@r-project.org
> *Subject:* Re: [R] Request for R Assistance: Downloading Data
>
> I think this hunch is off the mark... the file name is fine as it is... if
> anything will confuse R it would be that the data inside the file are not
> what was expected.
>
> If in fact the file is csv formatted then the function to read it would be
> read.csv [1] or read.table [2]. Read the help pages for these functions and
> read the R Data Import/Export documentation [3].
>
> [1] ?read.csv at R console
> [2] ?read.table many of the options for this function will work for
> read.csv.
> [3] https://cran.r-project.org/doc/manuals/r-release/R-data.html
> R Data Import/Export
> 
> cran.r-project.org
> 1.1 Imports. The easiest form of data to import into R is a simple text
> file, and this will often be acceptable for problems of small or medium
> scale.
>
>
>
> On August 19, 2018 12:16:14 PM PDT, "Sparks, John" 
> wrote:
> >Just a hunch, but I would recommend simplifying your filename:  remove
> >the (CSV) portion.  It could be confusing in R read syntax.  Create a
> >filename with no unnecessary punctuation and no blank spaces.
> >
> >
> >--John Sparks
> >
> >
> >
> >From: R-help  on behalf of Spencer
> >Brackett 
> >Sent: Sunday, August 19, 2018 2:11 PM
> >To: r-help@r-project.org
> >Subject: [R] Request for R Assistance: Downloading Data
> >
> >Good evening,
> >
> >I am attempting to download Genomic data from the GDC onto R for
> >analysis
> >and am experiencing some difficulty. I have downloaded the GDC data
> >into an
> >Excel, CSV, and notepad (.txt) file and implemented what I believe to
> >be
> >the proper arguments, with every attempting failing to properly load
> >the
> >data onto R. The following is the various attempts I made in trying to
> >take
> >one of these files (a translated version of the GDC data) and load it
> >into R
> >.
> >
> >> load("C:\\Users\\Spencer\\Desktop\\LGG Drug (CSV).csv")
> >Error in load("C:\\Users\\Spencer\\Desktop\\LGG Drug (CSV).csv") :
> >bad restore file magic number (file may be corrupted) -- no data loaded
> >In addition: Warning message:
> >file �LGG Drug (CSV).csv� has magic number 'MANIF'
> >  Use of save versions prior to 2 is deprecated
> >> LGG Drug<-read.table("C:\\Users\\Spencer\\Desktop\\LGG Drug
> >(CSV).csv",header=TRUE,sep=",")
> >Error: unexpected symbol in "LGG Drug"
> >> LGG Drug<-read.table("C:
> >Error: unexpected symbol in "LGG Drug"
> >> load("C:\\Users\\Spencer\\Desktop\\DRUG TRIAL GBM.txt")
> >Error in load("C:\\Users\\Spencer\\Desktop\\DRUG TRIAL GBM.txt") :
> >bad restore file magic number (file may be corrupted) -- no data loaded
> >In addition: Warning message:
> >file �DRUG TRIAL GBM.txt� has magic number 'MANIF'
> >  Use of save versions prior to 2 is deprecated
> >> GBM Drug<-read.table("C:\\Users\\Spencer\\Desktop\\DRUG TRIAL
> >GBM.txt",header=TRUE,sep="")
> >Error: unexpected symbol in "GBM Drug"
> >> GBM Drug<-read.table("C:\\Users\\Spencer\\Desktop\\DRUG TRIAL
> >GBM.txt",header=TRUE,sep="\t")
> >Error: unexpected symbol in "GBM Drug"
> >> GBM Drug<-read.table("C:\\Users\\Spencer\\Desktop\\DRUG TRIAL
> >GBM.txt",header=TRUE,sep="")
> >Error: unexpected symbol in "GBM Drug"
> >>  GBM Drug<-read.table("C:\\Users\\Spencer\\Desktop\\DRUG TRIAL
> >GBM.txt",header=TRUE,sep="\t")
> >Error: unexpected symbol in " GBM Drug"
> >> load("C:\\Users\\Spencer\\Desktop\\DRUG TRIAL GBM(word wrap).txt")
> >Error in load("C:\\Users\\Spencer\\Desktop\\DRUG TRIAL GBM(word
> >wrap).txt")
> >:
> >bad restore file magic number (file may be corrupted) -- no data loaded
> >In addition: Warning message:
> >file �DRUG TRIAL GBM(word wrap).txt� has magic number 'MANIF'
> >  Use of save versions prior to 2 is deprecated
> >> GBM Drug<-read.table("C:\\Users\\Spencer\\Desktop\\DRUG TRIAL
> >GBM(word
> >wrap).txt",header=TRUE,sep="")
> >Error: unexpected symbol in "GBM Drug"
> >
> >Any insight into what perhaps I am inputting that is causes this
> >reoccurring error? Any suggestions as to another procedure for moving
> >forward would be greatly appreciated!
> >
> >Many thanks,
> >
> >Spencer Brackett
> >
> >[[alternative HTML version deleted]]
> >
> >__
> >R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> >https://stat.ethz.ch/mailman/listinfo/r-help
> >R-help -- Main R Mailing List: Primary help - Homepage -
> >SfS
> >stat.

[R] Fwd: Computing the density of a median

2018-08-20 Thread Dioggban Jakperik
Dear all,


I have the following function

kdenor <- function(aa,q=NULL){
a=sample(aa,500,replace=F)
ab=quantile(a, p=0.75)-quantile(a, p=0.25)
h=(0.9*min(var(a),ab))/(1.34*n^(1/5))

if(is.null(q)) {
q = seq(min(a)-3*h, max(a)+3*h, length.out=length(a))
}
nx = length(a)
nq = length(q)
xmat = matrix(q,nq,nx) - matrix(a,nq,nx,byrow=TRUE)
denall= dnorm(xmat/h)/h
denhat = apply(denall,1,mean)

f<-denhat
f1<-median(f)
#das<-list(x=q, y=denhat, h=h)
#return(das)
}

f1<-kdenor(aa)

My interest is to obtain the estimate of the density at the median of the
sample data.
But the output of the current function  doesn't provide the correct result.
Kindly help.
Regards.


-- 
Jakperik Dioggban (Student, PAUISTI)
PhD Mathematics (Statistics Option)
Determination is Key to Success



-- 
Jakperik Dioggban (Student, PAUISTI)
PhD Mathematics (Statistics Option)
Determination is Key to Success

[[alternative HTML version deleted]]

__
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] Transforming data for nice output table

2018-08-20 Thread Jim Lemon
Hi David,
As you want the _values_ of Year from the initial data frame appended
to the _names_ of GW_Elevation, you can't do it the easy way:

dddf<-read.table(text="LocationDateYear  GW_Elevation
127(I)5/14/2006 2006   752.46
119(I)5/14/2006 2006   774.67
127(I)6/11/2007 2007   752.06
119(I)6/11/2007 2007   775.57",
header=TRUE)
library(prettyR)
# easy part
sdddf<-stretch_df(dddf[c(1,3,4)],"Location",c("Year","GW_Elevation"))
sdddf

This only works for a data frame with the structure and names of the initial one

# hard part
sdddf_dim<-dim(sdddf)
nyears<-(sdddf_dim[2] - 1)/2
fsdddf<-sdddf[,c(1,1:nyears+nyears+1)]
names(fsdddf)<-c("Location",paste("GW_Elevation",unique(dddf$Year),sep="_"))
fsdddf

I would strongly suggest being happy with the easy way, because if the
order of years isn't ascending, the hard way won't work.

Jim

On Tue, Aug 21, 2018 at 5:17 AM, David Doyle  wrote:
> Hello everyone,
>
> I'm trying to generate tables of my data out of R for my report.
>
> My data is setup in the format as follows and the example can be found at:
> http://doylesdartden.com/R/ExampleData.csv
>
> LocationDateYear  GW_Elevation
> 127(I)5/14/2006 2006   752.46
> 119(I)5/14/2006 2006   774.67
> 127(I)6/11/2007 2007   752.06
> 119(I)6/11/2007 2007   775.57
>
> I would like to generate a table that showed
>
> LocationGW_Elevation 2006GW_Elevation 2007GW_Elevation xxx.
>
> 119(I)774.67  775.57
>   
> 127(I)752.46  752.06
>   
>   XX   XX
>
>  Any thoughts on how to transform the data so it would be in this format??
>
> Thank you for your time
>
> David Doyle
>
> [[alternative HTML version deleted]]
>
> __
> 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] plotmath and logical operators?

2018-08-20 Thread Bert Gunter
This is clumsy and probably subject to considerable improvement, but does
it work for you:

left <- quote(x >= 3)
right <- quote(y <= 3) ## these can be anything

## the plot:
plot(1)
eval(substitute(mtext(expression(paste(left, " & ",right))), list(left =
left, right = right)))

## Expression evaluation
eval(substitute(with(df,left & right), list(left = left, right = right)))

Cheers,
Bert


Bert Gunter

"The trouble with having an open mind is that people keep coming along and
sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Mon, Aug 20, 2018 at 2:00 PM MacQueen, Don via R-help <
r-help@r-project.org> wrote:

> I would like to use plotmath to annotate a plot with an expression that
> includes a logical operator.
>
> ## works well
> tmp <- expression(x >= 3)
> plot(1)
> mtext(tmp)
>
> ## not so well
> tmp <- expression(x >= 3 &  y <= 3)
> plot(1)
> mtext(tmp)
>
> Although the text that's displayed makes sense, it won't be obvious to my
> non-mathematical audience.
>
> I'd appreciate suggestions.
>
>
> I've found a work-around that gets the annotation to look right
>   tmpw <- expression(paste( x >= 3, " & ", y <= 3) )
>   plot(1)
>   mtext(tmpw)
>
>
> But it breaks my original purpose, illustrated by this example:
>
> df <- data.frame(x=1:5, y=1:5)
> tmp <- expression(x >= 3 & y <= 3)
> tmpw <- expression(paste( x >= 3, " & ", y <= 3) )
> with(df, eval(tmp))
> [1] FALSE FALSE  TRUE FALSE FALSE
> with(df, eval(tmpw))
> [1] "FALSE  &  TRUE" "FALSE  &  TRUE" "TRUE  &  TRUE"  "TRUE  &  FALSE"
> "TRUE  &  FALSE"
>
> Thanks
> -Don
>
> --
> Don MacQueen
> Lawrence Livermore National Laboratory
> 7000 East Ave., L-627
> Livermore, CA 94550
> 925-423-1062
> Lab cell 925-724-7509
>
>
>
> __
> 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.
>

[[alternative HTML version deleted]]

__
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] Transforming data for nice output table

2018-08-20 Thread Jeff Newmiller
If departing from base R into contributed territory, tidyr::spread is 
well-suited to this.


library(dplyr)
library(tidyr)
dta <- read.csv( "http://doylesdartden.com/R/ExampleData.csv";
   , header = TRUE
   , as.is = TRUE
   )
result <- (   dta # starting with your data...
  # keep only relevant columns
  %>% select( Location, Year, GW_Elevation )
  # make the key column look like your desired column names
  %>% mutate( Year = sprintf( "GW_Elevation %d", Year ) )
  # spread the "long" data out "wide"
  %>% spread( Year, GW_Elevation )
  )

On Tue, 21 Aug 2018, Jim Lemon wrote:


Hi David,
As you want the _values_ of Year from the initial data frame appended
to the _names_ of GW_Elevation, you can't do it the easy way:

dddf<-read.table(text="LocationDateYear  GW_Elevation
127(I)5/14/2006 2006   752.46
119(I)5/14/2006 2006   774.67
127(I)6/11/2007 2007   752.06
119(I)6/11/2007 2007   775.57",
header=TRUE)
library(prettyR)
# easy part
sdddf<-stretch_df(dddf[c(1,3,4)],"Location",c("Year","GW_Elevation"))
sdddf

This only works for a data frame with the structure and names of the initial one

# hard part
sdddf_dim<-dim(sdddf)
nyears<-(sdddf_dim[2] - 1)/2
fsdddf<-sdddf[,c(1,1:nyears+nyears+1)]
names(fsdddf)<-c("Location",paste("GW_Elevation",unique(dddf$Year),sep="_"))
fsdddf

I would strongly suggest being happy with the easy way, because if the
order of years isn't ascending, the hard way won't work.

Jim

On Tue, Aug 21, 2018 at 5:17 AM, David Doyle  wrote:

Hello everyone,

I'm trying to generate tables of my data out of R for my report.

My data is setup in the format as follows and the example can be found at:
http://doylesdartden.com/R/ExampleData.csv

LocationDateYear  GW_Elevation
127(I)5/14/2006 2006   752.46
119(I)5/14/2006 2006   774.67
127(I)6/11/2007 2007   752.06
119(I)6/11/2007 2007   775.57

I would like to generate a table that showed

LocationGW_Elevation 2006GW_Elevation 2007GW_Elevation xxx.

119(I)774.67  775.57
  
127(I)752.46  752.06
  
  XX   XX

 Any thoughts on how to transform the data so it would be in this format??

Thank you for your time

David Doyle

[[alternative HTML version deleted]]

__
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.



---
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

__
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] plotmath and logical operators?

2018-08-20 Thread MacQueen, Don via R-help
Thanks Bert!

It certainly works for the example (and shows a much deeper understanding of 
eval, substitute, etc. than I have). But it doesn't appear to generalize very 
well in the way I need (which of course I didn't think of mentioning until 
after I sent the email -- sorry).

Suppose subs is any expression that would be valid for the subset argument of 
base::subset, for a given data frame. Then I can extract that subset of the 
data frame by using
   mydf[  with(mydf, eval(subs)) ,  ]
(or similar).

Then, having plotted some aspect of that subset, I want to annotate the plot 
with the subset specifications.

I've used this approach to  set up a system that helps me to interactively 
review various subsets of a large set of data. I save the final selected 
subsetting expressions in some sort of data structure, for later use in 
preparing a report using rmarkdown.

I was hoping to use plotmath to improve the appearance of the annotations -- 
but I now think it's not worth this kind of effort. I think I'm going to settle 
for mtext( as.character(subs) ).

-Don

--
Don MacQueen
Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062
Lab cell 925-724-7509



From: Bert Gunter 
Date: Monday, August 20, 2018 at 3:38 PM
To: "MacQueen, Don" 
Cc: array R-help 
Subject: Re: [R] plotmath and logical operators?

This is clumsy and probably subject to considerable improvement, but does it 
work for you:

left <- quote(x >= 3)
right <- quote(y <= 3) ## these can be anything

## the plot:
plot(1)
eval(substitute(mtext(expression(paste(left, " & ",right))), list(left = left, 
right = right)))

## Expression evaluation
eval(substitute(with(df,left & right), list(left = left, right = right)))
Cheers,
Bert


Bert Gunter

"The trouble with having an open mind is that people keep coming along and 
sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Mon, Aug 20, 2018 at 2:00 PM MacQueen, Don via R-help 
mailto:r-help@r-project.org>> wrote:
I would like to use plotmath to annotate a plot with an expression that 
includes a logical operator.

## works well
tmp <- expression(x >= 3)
plot(1)
mtext(tmp)

## not so well
tmp <- expression(x >= 3 &  y <= 3)
plot(1)
mtext(tmp)

Although the text that's displayed makes sense, it won't be obvious to my 
non-mathematical audience.

I'd appreciate suggestions.


I've found a work-around that gets the annotation to look right
  tmpw <- expression(paste( x >= 3, " & ", y <= 3) )
  plot(1)
  mtext(tmpw)


But it breaks my original purpose, illustrated by this example:

df <- data.frame(x=1:5, y=1:5)
tmp <- expression(x >= 3 & y <= 3)
tmpw <- expression(paste( x >= 3, " & ", y <= 3) )
with(df, eval(tmp))
[1] FALSE FALSE  TRUE FALSE FALSE
with(df, eval(tmpw))
[1] "FALSE  &  TRUE" "FALSE  &  TRUE" "TRUE  &  TRUE"  "TRUE  &  FALSE" "TRUE  
&  FALSE"

Thanks
-Don

--
Don MacQueen
Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062
Lab cell 925-724-7509



__
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.

[[alternative HTML version deleted]]

__
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] plotmath and logical operators?

2018-08-20 Thread Bert Gunter
As I understand it, the problem is:

"A mathematical expression must obey the normal rules of syntax for
any *R* expression,
but it is interpreted according to very different rules than for normal *R*
expressions."

I believe this means that you cannot do what you wanted to using plotmath.

Cheers,
Bert


On Mon, Aug 20, 2018 at 4:14 PM MacQueen, Don  wrote:

> Thanks Bert!
>
>
>
> It certainly works for the example (and shows a much deeper understanding
> of eval, substitute, etc. than I have). But it doesn't appear to generalize
> very well in the way I need (which of course I didn't think of mentioning
> until after I sent the email -- sorry).
>
>
>
> Suppose subs is any expression that would be valid for the subset argument
> of base::subset, for a given data frame. Then I can extract that subset of
> the data frame by using
>
>mydf[  with(mydf, eval(subs)) ,  ]
>
> (or similar).
>
>
>
> Then, having plotted some aspect of that subset, I want to annotate the
> plot with the subset specifications.
>
>
>
> I've used this approach to  set up a system that helps me to interactively
> review various subsets of a large set of data. I save the final selected
> subsetting expressions in some sort of data structure, for later use in
> preparing a report using rmarkdown.
>
>
>
> I was hoping to use plotmath to improve the appearance of the annotations
> -- but I now think it's not worth this kind of effort. I think I'm going to
> settle for mtext( as.character(subs) ).
>
>
>
> -Don
>
>
>
> --
>
> Don MacQueen
>
> Lawrence Livermore National Laboratory
>
> 7000 East Ave., L-627
>
> Livermore, CA 94550
>
> 925-423-1062
>
> Lab cell 925-724-7509
>
>
>
>
>
>
>
> *From: *Bert Gunter 
> *Date: *Monday, August 20, 2018 at 3:38 PM
> *To: *"MacQueen, Don" 
> *Cc: *array R-help 
> *Subject: *Re: [R] plotmath and logical operators?
>
>
>
> This is clumsy and probably subject to considerable improvement, but does
> it work for you:
>
>
>
> left <- quote(x >= 3)
> right <- quote(y <= 3) ## these can be anything
>
>
>
> ## the plot:
>
> plot(1)
>
> eval(substitute(mtext(expression(paste(left, " & ",right))), list(left =
> left, right = right)))
>
>
>
> ## Expression evaluation
>
> eval(substitute(with(df,left & right), list(left = left, right = right)))
>
> Cheers,
>
> Bert
>
>
>
>
> Bert Gunter
>
> "The trouble with having an open mind is that people keep coming along and
> sticking things into it."
> -- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
>
>
>
>
>
> On Mon, Aug 20, 2018 at 2:00 PM MacQueen, Don via R-help <
> r-help@r-project.org> wrote:
>
> I would like to use plotmath to annotate a plot with an expression that
> includes a logical operator.
>
> ## works well
> tmp <- expression(x >= 3)
> plot(1)
> mtext(tmp)
>
> ## not so well
> tmp <- expression(x >= 3 &  y <= 3)
> plot(1)
> mtext(tmp)
>
> Although the text that's displayed makes sense, it won't be obvious to my
> non-mathematical audience.
>
> I'd appreciate suggestions.
>
>
> I've found a work-around that gets the annotation to look right
>   tmpw <- expression(paste( x >= 3, " & ", y <= 3) )
>   plot(1)
>   mtext(tmpw)
>
>
> But it breaks my original purpose, illustrated by this example:
>
> df <- data.frame(x=1:5, y=1:5)
> tmp <- expression(x >= 3 & y <= 3)
> tmpw <- expression(paste( x >= 3, " & ", y <= 3) )
> with(df, eval(tmp))
> [1] FALSE FALSE  TRUE FALSE FALSE
> with(df, eval(tmpw))
> [1] "FALSE  &  TRUE" "FALSE  &  TRUE" "TRUE  &  TRUE"  "TRUE  &  FALSE"
> "TRUE  &  FALSE"
>
> Thanks
> -Don
>
> --
> Don MacQueen
> Lawrence Livermore National Laboratory
> 7000 East Ave., L-627
> Livermore, CA 94550
> 925-423-1062
> Lab cell 925-724-7509
>
>
>
> __
> 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.
>
>

[[alternative HTML version deleted]]

__
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] plotmath and logical operators?

2018-08-20 Thread William Dunlap via R-help
A generalization of Bert's suggestion is

plotSubset <- function (data, subset, qsubset = substitute(subset))
{
sdata <- data[eval(qsubset, data), ]
with(sdata, plot(x, y, main = subsetToPlotmath(expr = qsubset)))
}


subsetToPlotmath <- function(expr) {
# Argument 'expr': an expression used as subset argument to subset()
# Return: an expression used by plotmath that is more readable to
non-programming people
if (is.call(expr)) {
for(i in seq_along(expr)) {
expr[[i]] <- subsetToPlotmath(expr[[i]])
}
if (is.name(funcName <- expr[[1]]) && !is.null(func <-
env.subsetToPlotmath[[as.character(funcName)]])) {
expr <- do.call(func, as.list(expr[-1]))
}
}
expr
}
env.subsetToPlotmath <- new.env()
env.subsetToPlotmath[["&"]] <- function(x, y) substitute(x ~ italic(and) ~
y)
env.subsetToPlotmath[["|"]] <- function(x, y) substitute((x) ~ italic(or) ~
(y)) # internal parens not always needed
env.subsetToPlotmath[["log10"]] <- function(x)
substitute(italic(log)[10](x))
env.subsetToPlotmath[["exp"]] <- function(x) substitute(italic(e)^x)

You can add more conversions to the environment env.subsetToPlotmath.

Try it with

> df <- data.frame(x=1:5, y=1:5)
> plotSubset(df, x<1.5 | y>3.5) # see title "(x < 1.5) or (y > 3.5)" and
pts at x=1,4,5.

It doesn't get right the parentheses needed to enforce the order of
evaluation:
it always puts parentheses around the arguments to | and never puts them
around the arguments to &.

Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Mon, Aug 20, 2018 at 4:14 PM, MacQueen, Don via R-help <
r-help@r-project.org> wrote:

> Thanks Bert!
>
> It certainly works for the example (and shows a much deeper understanding
> of eval, substitute, etc. than I have). But it doesn't appear to generalize
> very well in the way I need (which of course I didn't think of mentioning
> until after I sent the email -- sorry).
>
> Suppose subs is any expression that would be valid for the subset argument
> of base::subset, for a given data frame. Then I can extract that subset of
> the data frame by using
>mydf[  with(mydf, eval(subs)) ,  ]
> (or similar).
>
> Then, having plotted some aspect of that subset, I want to annotate the
> plot with the subset specifications.
>
> I've used this approach to  set up a system that helps me to interactively
> review various subsets of a large set of data. I save the final selected
> subsetting expressions in some sort of data structure, for later use in
> preparing a report using rmarkdown.
>
> I was hoping to use plotmath to improve the appearance of the annotations
> -- but I now think it's not worth this kind of effort. I think I'm going to
> settle for mtext( as.character(subs) ).
>
> -Don
>
> --
> Don MacQueen
> Lawrence Livermore National Laboratory
> 7000 East Ave., L-627
> Livermore, CA 94550
> 925-423-1062
> Lab cell 925-724-7509
>
>
>
> From: Bert Gunter 
> Date: Monday, August 20, 2018 at 3:38 PM
> To: "MacQueen, Don" 
> Cc: array R-help 
> Subject: Re: [R] plotmath and logical operators?
>
> This is clumsy and probably subject to considerable improvement, but does
> it work for you:
>
> left <- quote(x >= 3)
> right <- quote(y <= 3) ## these can be anything
>
> ## the plot:
> plot(1)
> eval(substitute(mtext(expression(paste(left, " & ",right))), list(left =
> left, right = right)))
>
> ## Expression evaluation
> eval(substitute(with(df,left & right), list(left = left, right = right)))
> Cheers,
> Bert
>
>
> Bert Gunter
>
> "The trouble with having an open mind is that people keep coming along and
> sticking things into it."
> -- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
>
>
> On Mon, Aug 20, 2018 at 2:00 PM MacQueen, Don via R-help <
> r-help@r-project.org> wrote:
> I would like to use plotmath to annotate a plot with an expression that
> includes a logical operator.
>
> ## works well
> tmp <- expression(x >= 3)
> plot(1)
> mtext(tmp)
>
> ## not so well
> tmp <- expression(x >= 3 &  y <= 3)
> plot(1)
> mtext(tmp)
>
> Although the text that's displayed makes sense, it won't be obvious to my
> non-mathematical audience.
>
> I'd appreciate suggestions.
>
>
> I've found a work-around that gets the annotation to look right
>   tmpw <- expression(paste( x >= 3, " & ", y <= 3) )
>   plot(1)
>   mtext(tmpw)
>
>
> But it breaks my original purpose, illustrated by this example:
>
> df <- data.frame(x=1:5, y=1:5)
> tmp <- expression(x >= 3 & y <= 3)
> tmpw <- expression(paste( x >= 3, " & ", y <= 3) )
> with(df, eval(tmp))
> [1] FALSE FALSE  TRUE FALSE FALSE
> with(df, eval(tmpw))
> [1] "FALSE  &  TRUE" "FALSE  &  TRUE" "TRUE  &  TRUE"  "TRUE  &  FALSE"
> "TRUE  &  FALSE"
>
> Thanks
> -Don
>
> --
> Don MacQueen
> Lawrence Livermore National Laboratory
> 7000 East Ave., L-627
> Livermore, CA 94550
> 925-423-1062
> Lab cell 925-724-7509
>
>
>
> __
> R-help@r-project.org

Re: [R] Transforming data for nice output table

2018-08-20 Thread Rui Barradas

Hello,

One of those would be with package reshape2.



dta <- read.csv( "http://doylesdartden.com/R/ExampleData.csv";)

subdta <- dta[, c("Location", "Year", "GW_Elevation")]

res <- reshape2::dcast(subdta, Location ~ Year, value.var = "GW_Elevation")
names(res)[-1] <- paste("GW_Elevation", names(res)[-1], sep = "_")
head(res)


Hope this helps,

Rui Barradas

On 20/08/2018 21:37, Rui Barradas wrote:

Hello,

This is a very frequent question.
I could rewrite one or two answers taken from StackOverflow:

https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format 




But there you will have more options.


Hope this helps,

Rui Barradas

On 20/08/2018 20:17, David Doyle wrote:

Hello everyone,

I'm trying to generate tables of my data out of R for my report.

My data is setup in the format as follows and the example can be found 
at:

http://doylesdartden.com/R/ExampleData.csv

Location    Date    Year  GW_Elevation
127(I)    5/14/2006 2006   752.46
119(I)    5/14/2006 2006   774.67
127(I)    6/11/2007 2007   752.06
119(I)    6/11/2007 2007   775.57

I would like to generate a table that showed

Location    GW_Elevation 2006    GW_Elevation 2007    GW_Elevation 
xxx.


119(I)    774.67  775.57
   
127(I)    752.46  752.06
   
  XX   XX

  Any thoughts on how to transform the data so it would be in this 
format??


Thank you for your time

David Doyle

[[alternative HTML version deleted]]

__
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.



---
This email has been checked for viruses by AVG.
https://www.avg.com

__
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] Transforming data for nice output table

2018-08-20 Thread Rui Barradas

Sorry, there is no need to subset the data frame,

reshape2::dcast(dta, etc)

will do the same.

Rui Barradas

On 21/08/2018 05:10, Rui Barradas wrote:

Hello,

One of those would be with package reshape2.



dta <- read.csv( "http://doylesdartden.com/R/ExampleData.csv";)

subdta <- dta[, c("Location", "Year", "GW_Elevation")]

res <- reshape2::dcast(subdta, Location ~ Year, value.var = "GW_Elevation")
names(res)[-1] <- paste("GW_Elevation", names(res)[-1], sep = "_")
head(res)


Hope this helps,

Rui Barradas

On 20/08/2018 21:37, Rui Barradas wrote:

Hello,

This is a very frequent question.
I could rewrite one or two answers taken from StackOverflow:

https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format 




But there you will have more options.


Hope this helps,

Rui Barradas

On 20/08/2018 20:17, David Doyle wrote:

Hello everyone,

I'm trying to generate tables of my data out of R for my report.

My data is setup in the format as follows and the example can be 
found at:

http://doylesdartden.com/R/ExampleData.csv

Location    Date    Year  GW_Elevation
127(I)    5/14/2006 2006   752.46
119(I)    5/14/2006 2006   774.67
127(I)    6/11/2007 2007   752.06
119(I)    6/11/2007 2007   775.57

I would like to generate a table that showed

Location    GW_Elevation 2006    GW_Elevation 2007    GW_Elevation 
xxx.


119(I)    774.67  775.57
   
127(I)    752.46  752.06
   
  XX   XX

  Any thoughts on how to transform the data so it would be in this 
format??


Thank you for your time

David Doyle

[[alternative HTML version deleted]]

__
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.



---
This email has been checked for viruses by AVG.
https://www.avg.com

__
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-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] plotmath and logical operators?

2018-08-20 Thread Richard M. Heiberger
## I would use microplot in this situation.
## This example produces a pdf file containing the graph.

library(lattice)
library(microplot)

## Hmisc options for pdflatex
## graphics files are .pdf
latexSetOptions()

RtoLatex <- function(subset , subset.char=substitute(subset)) {
  ## you might need some gsub calls in here
  paste0("$", subset.char, "$")
}

plotSubsetLatex <- function (data, subset, qsubset = substitute(subset),
 ...) {
  sdata <- data[eval(qsubset, data), ]
  myplot <- xyplot( y ~ x , data=sdata)
  latex(myplot,
## caption=RtoLatex(subset.char=deparse(qsubset)),  ## use
either caption or colheads
colheads=paste("\\Large \\strut",   ##
Hmisc::latex argument
   RtoLatex(subset.char=deparse(qsubset))),
collapse=identity, ## collapse is an argument to microplot()
x.axis=FALSE, y.axis=FALSE, ## x.axis, y.axis are arguments to
as.includegraphics()
...) ## arguments to latex() or as.includegraphics() or microplot()
  }


df <- data.frame(x=1:5, y=1:5)
myplot.tex <- plotSubsetLatex(df, x<1.5 | y>3.5, ## see title "(x <
1.5) | (y > 3.5)" and pts at x=1,4,5.
  height.panel=3, width.panel=3, rowname=NULL)
myplot.tex$file ## pathname to tex file which contains pathname to
component pdf file
## print.default(myplot.tex) ## pathname to tex file and additional
information about component pdf files
myplot.tex ## displays generated pdf file on screen, and pathname to
generated pdf file

On Mon, Aug 20, 2018 at 10:12 PM, William Dunlap via R-help
 wrote:
> A generalization of Bert's suggestion is
>
> plotSubset <- function (data, subset, qsubset = substitute(subset))
> {
> sdata <- data[eval(qsubset, data), ]
> with(sdata, plot(x, y, main = subsetToPlotmath(expr = qsubset)))
> }
>
>
> subsetToPlotmath <- function(expr) {
> # Argument 'expr': an expression used as subset argument to subset()
> # Return: an expression used by plotmath that is more readable to
> non-programming people
> if (is.call(expr)) {
> for(i in seq_along(expr)) {
> expr[[i]] <- subsetToPlotmath(expr[[i]])
> }
> if (is.name(funcName <- expr[[1]]) && !is.null(func <-
> env.subsetToPlotmath[[as.character(funcName)]])) {
> expr <- do.call(func, as.list(expr[-1]))
> }
> }
> expr
> }
> env.subsetToPlotmath <- new.env()
> env.subsetToPlotmath[["&"]] <- function(x, y) substitute(x ~ italic(and) ~
> y)
> env.subsetToPlotmath[["|"]] <- function(x, y) substitute((x) ~ italic(or) ~
> (y)) # internal parens not always needed
> env.subsetToPlotmath[["log10"]] <- function(x)
> substitute(italic(log)[10](x))
> env.subsetToPlotmath[["exp"]] <- function(x) substitute(italic(e)^x)
>
> You can add more conversions to the environment env.subsetToPlotmath.
>
> Try it with
>
>> df <- data.frame(x=1:5, y=1:5)
>> plotSubset(df, x<1.5 | y>3.5) # see title "(x < 1.5) or (y > 3.5)" and
> pts at x=1,4,5.
>
> It doesn't get right the parentheses needed to enforce the order of
> evaluation:
> it always puts parentheses around the arguments to | and never puts them
> around the arguments to &.
>
> Bill Dunlap
> TIBCO Software
> wdunlap tibco.com
>
> On Mon, Aug 20, 2018 at 4:14 PM, MacQueen, Don via R-help <
> r-help@r-project.org> wrote:
>
>> Thanks Bert!
>>
>> It certainly works for the example (and shows a much deeper understanding
>> of eval, substitute, etc. than I have). But it doesn't appear to generalize
>> very well in the way I need (which of course I didn't think of mentioning
>> until after I sent the email -- sorry).
>>
>> Suppose subs is any expression that would be valid for the subset argument
>> of base::subset, for a given data frame. Then I can extract that subset of
>> the data frame by using
>>mydf[  with(mydf, eval(subs)) ,  ]
>> (or similar).
>>
>> Then, having plotted some aspect of that subset, I want to annotate the
>> plot with the subset specifications.
>>
>> I've used this approach to  set up a system that helps me to interactively
>> review various subsets of a large set of data. I save the final selected
>> subsetting expressions in some sort of data structure, for later use in
>> preparing a report using rmarkdown.
>>
>> I was hoping to use plotmath to improve the appearance of the annotations
>> -- but I now think it's not worth this kind of effort. I think I'm going to
>> settle for mtext( as.character(subs) ).
>>
>> -Don
>>
>> --
>> Don MacQueen
>> Lawrence Livermore National Laboratory
>> 7000 East Ave., L-627
>> Livermore, CA 94550
>> 925-423-1062
>> Lab cell 925-724-7509
>>
>>
>>
>> From: Bert Gunter 
>> Date: Monday, August 20, 2018 at 3:38 PM
>> To: "MacQueen, Don" 
>> Cc: array R-help 
>> Subject: Re: [R] plotmath and logical operators?
>>
>> This is clumsy and probably subject to considerable improvement, but does
>> it work for you:
>>
>> left <- quote(x >= 3)
>> right <- quote(y <= 3) ## these can be anything

[R] (no subject)

2018-08-20 Thread Giuseppa Cefalu
Hello,

I have  a list of lists.  The lists in the list of lists are file names.  I
use lapply to read and merge the contents of each list in the list of lists
(3 merged contents in this case  which will be the content of 3 files).
Then, I  have to change the name of the 3 resulting files and finally I
have to write the contents of the files to each file.

 lc <- list("test.txt", "test.txt", "test.txt", "test.txt")
 lc1 <- list("test.txt", "test.txt", "test.txt")
 lc2 <- list("test.txt", "test.txt")
#list of lists.  The lists contain file names
 lc <- list(lc, lc1, lc2)
#new names for the three lists in the list of lists
 new_dataFns <- list("name1", "name2", "name3")
 file_paths <- NULL
 new_path <- NULL
#add the file names to the path and read and merge the contents of each
list in the list of lists
 lapply(
lc,
function(lc) {
 filenames <- file.path(dataFnsDir, lc)
 dataList= lapply(filenames, function (x) read.table(file=x,
header=TRUE))
 Reduce(function(x,y) merge(x,y), dataList)
 #   print(dataList)

}
  )

#add the new name of the file to the path total will be 3
paths/fille_newname.tsv.
 lapply(new_path, function(new_path){new_path <- file.path(getwd(),
new_dataFns)

The statements above work because lc and  new_dataFns are global and I can
pass them to the lapply function

#Finally, I need to write the merged contents to the corresponding file
(path/name.tsv).  I tried the following statement, but this does not work.
How can I write the content to each file? I was trying to use list <-
cbind(dataList, new_path) so that afterwards I can get the merged contents
and the file_name from the list and that way write each merged content to
the corresponding file, but it seems that the dataList and the newPath are
not global and the cbind() function does not work.

[[alternative HTML version deleted]]

__
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.