Re: [R] Discrete Uniform Distribution

2017-08-08 Thread Jeff Newmiller
Which step do you need HELP with? Read the Posting Guide... you should be 
posting plain-text-formatted emails, with example code and data showing how far 
you have come. This is not a free programming service. 

Of course if this is homework then you should be asking your instructor or 
other support staff for help. 
-- 
Sent from my phone. Please excuse my brevity.

On August 8, 2017 3:18:13 PM PDT, Muhammad-Usman Zaheer 
 wrote:
>Hey
>
>I want to generate a discrete uniform distribution as follows:
>
>For example:
>
>I want to get 278734 records each with a numbers between 7-10. And the
>sum
>of numbers in 278734 records to be equal to 2253712. Once this is done,
>I
>want to get that printed to an excel file such that
>
>Record Value
>19
>27
>so on
>278734 8
>
>
>The total for column "Value"=2253712
>
>​Thanks.​
>
>-- 
>
>
>
>
>
>Best,
>
>​m.u.zaheer​
>
>   [[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] Inheritance for S3 classes

2017-08-08 Thread Hadley Wickham
You might find http://adv-r.hadley.nz/s3.html to be helpful (in
particular, http://adv-r.hadley.nz/s3.html#constructors-1, gives my
advice about subclass constructors)

Hadley

On Mon, Aug 7, 2017 at 7:06 PM, Kym Nitschke  wrote:
> Hi R Users,
>
> I am relatively new to programming in R … so I apologise if my questions 
> appear ‘dumb’.
>
> I am using a package that defines a number of S3 classes. I want to create an 
> S3 child class of one of these classes. The parent class has a contractor 
> with many arguments. I have been having difficulty writing the child class 
> contractor. I have been unable to find a good reference in the internet for 
> writing S3 classes. What I have been able to find out so far is that the 
> child class constructor should call the parent class constructor … which in 
> this case requires passing the argument list with a variable number of 
> arguments (i.e. there are a number of optional arguments) from the child to 
> the parent.
>
> So my first question is … is there an easy way to do this? The match.call 
> function will return a call object .. however the attributes function when 
> used on the call object returns a ‘NULL’.
>
> My second question is … can any one recommend a good reference for object 
> oriented programming in R which includes a comprehensive discussion of the S3 
> class model?
>
> Thanks
>
> Regards,
>
> Kym
> __
> 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.



-- 
http://hadley.nz

__
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] Discrete Uniform Distribution

2017-08-08 Thread Muhammad-Usman Zaheer
Hey

I want to generate a discrete uniform distribution as follows:

For example:

I want to get 278734 records each with a numbers between 7-10. And the sum
of numbers in 278734 records to be equal to 2253712. Once this is done, I
want to get that printed to an excel file such that

Record Value
19
27
so on
278734 8


The total for column "Value"=2253712

​Thanks.​

-- 





Best,

​m.u.zaheer​

[[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] Latin hypercube sampling from a non-uniform distribution

2017-08-08 Thread Marine Regis
Thanks for your answer.

I have attached the plot for representing the variable. I think that I need to 
draw a Hypercube sample for each age class (i.e., for 0, 1, 2, 3, 4, 5, 6, 7) 
in a given simulation (i.e., N = 1) and the LHS values for all age classes 
should be like the observed cumulative distribution (see attached figure). 
Thus, the output of randomLHS should be a matrix with 100 rows (N = 100 
simulations) and 7 columns (7 age classes) containing LHS values and each row 
should exhibit the same pattern as the observed cumulative distribution.
With the command “qpois(X[, "mortality_probability"], 0.9)”, I don’t obtain a 
LHS value for each age class and the distribution is not a cumulative 
distribution as in the attached figure. So, I am afraid I don’t know how to do 
that.
Thanks so much for your time
Marine




De : S Ellison 
Envoyé : mardi 8 août 2017 14:48
À : Marine Regis; r-help@r-project.org
Objet : RE: Latin hypercube sampling from a non-uniform distribution

> However, my variable is simulated from the cumulative distribution function
> of the Poisson distribution.
Then I am afraid I don't know what you're trying to achieve.
Or why.

However, the principle holds; write a function that maps [0,1] to the 'pattern' 
you want, do that and apply it to the result from randomLHS.
It happens that for generating data that follow a given probability 
distribution F, that function is the quantile function for F so you often do 
not need to write it.






***
This email and any attachments are confidential. Any use, copying or
disclosure other than by the intended recipient is unauthorised. If
you have received this message in error, please notify the sender
immediately via +44(0)20 8943 7000 or notify postmas...@lgcgroup.com
and delete this message and any copies from your computer and network.
LGC Limited. Registered in England 2991879.
Registered office: Queens Road, Teddington, Middlesex, TW11 0LY, UK
__
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-es] unir varios archivos .csv en una serie historica

2017-08-08 Thread Carlos Ortega
Hola,

Para la próxima vez...:

https://cloud.r-project.org/web/packages/easycsv/index.html

Saludos,
Carlos Ortega
www.qualityexcellence.es

El 8 de agosto de 2017, 15:04, Sebastian Kruk 
escribió:

> Hola Eric. Muchas gracias. Era exactamente lo que quería. Te agradezco
> mucho. Saludos, Sebastián.
>
> Enviado desde Correo para Windows 10
>
> De: eric
> Enviado: martes, 8 de agosto de 2017 8:25
> Para: Sebastian Kruk; Lista R
> Asunto: Re: [R-es] unir varios archivos .csv en una serie historica
>
> hola sebastian, invente 3 archivos con la estructura que describes y probe
> el codigo, le hice un par de arreglos necesarios, ahi va ... funciona bien
> con los archivos que te adjunto:
> # usando la libreria data.table
> library(data.table)
> setwd("/tu/directorio/con/los/datos/")
> filenames <- list.files(path = "/tu/directorio/con/los/datos/")
>   # creas un data.table que contendra TODOS los datos de tus archivos
> datos <- data.table()
>   # ciclo para leer cada archivo
> i<-1
> for (i in 1:length(filenames))
> {
> # 1. leer los datos de un unico archivo
> data <- data.table()
> data <- fread(filenames[i], header=TRUE)
> # 2. transformar la estructura del archivo de filas con hora y
> columnas con dias a ( columna con dia, columna con hora y columna con
> precio )
>   # primero usar stack() ... suponiendo que tu primera columna de
> datos es la hora del dia y tiene encabezado "horas"
> data.stacked <- data[,cbind(hora,stack(data, select=-hora))]
> data.stacked <- as.data.table(data.stacked)
> setnames(data.stacked,c("ind","values"),c("dia","precio"))
> # 3. agregar la columna con el nombre del mes
> data.stacked[, mes:=as.character(substr(filenames[i],1,3))]
> # 4. uniendo los datos
> datos <- rbind(datos,data.stacked)
> i <- i+1
> }
> espero que te sirva,
> suerte !!!
> eric.
>
>
>
> On 08/08/2017 06:50 AM, Sebastian Kruk wrote:
> Hola Eric. Me diste una muy buena orientación.
> Para algunos años los archivos son de excel donde cada uno tiene 12 hojas,
> una hoja por mes.
>
> Cada hoja tiene el siguiente formato:
>
> Hora 1 2 3 4 … 31
> 1 0 0 0 0 … 23
> 2 0 0 0 24 … 0
> 3 0 0 0 24,5 … 21
> 4 0 0 0 26 … 12
> …
> 24 0 0 0 0 … 0
>
> Por ejemplo en el día 1 el precio en las horas 1, 2, 3, 4 y 24 es 0, en
> cambio el día 31 el precio a la hora 1 es 23, a las 2 es 0, a las 3 es 21,
> a las 4 es 12 y a las 24 es 0.
>
> Espero no haberlos confundido más.
>
> Gracias,
>
> Sebastián.
>
> Enviado desde mi teléfono con Windows 10
>
> De: eric
> Enviado: martes, 8 de agosto de 2017 6:52
> Para: Sebastian Kruk; Lista R
> Asunto: Re: [R-es] unir varios archivos .csv en una serie historica
>
> Hola sebastian, sin el archivo de datos para probar y ver la estructura de
> los datos es un poco dificil, pero haciendo algunas suposiciones imagino
> que algo como esto te puede ayudar, seguro tendras que hacer ajustes:
> # usando la libreria data.table
> library(data.table)
> filenames <- list.files(path = "/tu/path")
>   # creas un data.table que contendra TODOS los datos de tus archivos
> datos <- data.table()
>   # ciclo para leer cada archivo
> i<-1
> for (i in 1:length(filenames))
> {
> # 0. crear un data.table para contener los datos de tu archivo de
> forma temporal dentro del ciclo
> data <- data.table()
> # 1. leer los datos de un unico archivo
> data <- as.data.table(fread(filenames[i], header=TRUE))
>
> # 2. transformar la estructura del archivo de filas con hora y
> columnas con dias a ( columna con dia, columna con hora y columna con
> precio )
>   # primero usar stack() ... suponiendo que tu primera columna de
> datos es la hora del dia y tiene encabezado "horas"
> data.stacked <- data[,cbind(horas,stack(data, select=-horas))]
> data.stacked <- as.data.table(data.stacked)
>
> # 3. agregar la columna con el nombre del mes
> data.stacked[, mes:=as.character(substr(filenames[i],
> posiciondelPRIMERcaracterdelnombredelmes,posiciondelULTIMOcaracterdelno
> mbredelmes))]
>
> # 4. uniendo los datos
> datos <- rbind(datos,data)
> i <- i+1
> }
> Ojala te sirva,
> Suerte 
> Eric.
>
>
>
> On 08/07/2017 06:17 PM, Sebastian Kruk wrote:
> Estimados usuarios-R:
>
> Muy buenas noches.
>
> Tengo una serie de archivos csv que contienen los precios mayoristas de
> electricidad por hora.
>
> Cada archivo csv corresponde a un mes de un cierto año.
>
> Cada columna corresponde a un día del mes y cada fila a una hora del día (1
> a 24 horas).
>
> ¿Hay alguna forma rápida de importar todos los datos y formar un vector
> columna en que cada observación corresponde al precio que se dio en cierta
> hora en cierto dia en cierto mes en cierto año?
>
> Desde ya muchas gracias,
>
> Sebastián.
>
>   [[alternative HTML version deleted]]
>
> ___
> R-help-es mailing list
> R-help-es@r-project.org
> 

[R] Problem with serialization via readRDS() on a textConnection()

2017-08-08 Thread Christopher Walker
Hi All,

I had working code under R v3.2 that serialized an object, stored the
serialized object in a database, and then successfully retrieved and
hydrated that object.

I recently updated to R v3.4.1 and the same code now fails.

Here is the code in question (simplified), and the resulting error:


> zz = textConnection('tempConnection', 'wb')
> saveRDS(c("a", "b", "c"), zz, ascii = TRUE)
> serialized_obj = paste(textConnectionValue(zz), collapse='\n')
> readRDS(textConnection(serialized_obj))
Error in gzcon(file) : 'read' not enabled for this connection


Docs haven't been much help in this case. I've tried a number of variations
but no luck. readRDS() was updated in v3.4.1, but I'm hesitant to call this
a bug without intimate knowledge of the source. Any help would be greatly
appreciated.

[[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] Bug?

2017-08-08 Thread William Dunlap via R-help
I think the help file for apply() warns you that if you give it a
data.frame, the data.frame will be converted to a matrix, with X <-
as.matrix(X), before FUN is called on its rows or columns.  Look at what
as.matrix does to your data: since there is a non-numeric column it
produces a character matrix and since in the second example some numbers
have 2 digits, the other numbers have a leading space.

> as.matrix(a[1:2,])
  row column assayplate
1 "B" "2""Assay1" "1"
2 "C" "2""Assay1" "1"
> as.matrix(a[1:3,])
  row column assayplate
1 "B" " 2"   "Assay1" "1"
2 "C" " 2"   "Assay1" "1"
3 "B" "10"   "Assay1" "1"

I avoid using apply() on data.frames.


Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Tue, Aug 8, 2017 at 11:39 AM, Ramiro Barrantes <
ram...@precisionbioassay.com> wrote:

> Hello,
>
> In my code I found something that looks like an anomaly, I found a
> reproducible example in which I am just trying to compare each row in a
> data frame against the first row:
>
> a<-data.frame(row=c("B","C","B"),column=c(2,2,10),assay=c("
> Assay1","Assay1","Assay1"),plate=c(1,1,1),stringsAsFactors=FALSE)
> apply(a[1:2,],1,function(x) { all(x==a[1,]) })
> apply(a[1:3,],1,function(x) { all(x==a[1,]) })
> > > 1 2
>  TRUE FALSE
> > 1 2 3
> FALSE FALSE FALSE
> >
>
> The second result is not right, it should be TRUE FALSE FALSE
>
> Am I doing something wrong or is this a bug?  With other inputs it seems
> to work ok
>
> Here is my sessionInfo()
> > sessionInfo()
> R version 3.2.5 (2016-04-14)
> Platform: x86_64-redhat-linux-gnu (64-bit)
> Running under: CentOS release 6.9 (Final)
>
> 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
> >
>
> Thank you,
> Ramiro
>
>
>
> Ramiro Barrantes Ph.D.
> Precision Bioassay, Inc.
> 431 Pine St., Suite 110
> Burlington, VT 05401
> 802 865 0155
> 802 861 2365 FAX
> www.precisionbioassay.com net/owa/redir.aspx?SURL=wN3KzpoKXAcetH7sTOTnSyfg-
> iAXFIinpPUtRcduCFCtkgZrUSDTCGgAdAB0AHAAOgAvAC8AdwB3AHcALgBwA
> HIAZQBjAGkAcwBpAG8AbgBiAGkAbwBhAHMAcwBhAHkALgBjAG8AbQA.=
> http%3a%2f%2fwww.precisionbioassay.com>
> ram...@precisionbioassay.com
>
> CONFIDENTIALITY NOTICE: This email, including any attach...{{dropped:9}}
>
> __
> 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.


[R] Bug?

2017-08-08 Thread Ramiro Barrantes
Hello,

In my code I found something that looks like an anomaly, I found a reproducible 
example in which I am just trying to compare each row in a data frame against 
the first row:

a<-data.frame(row=c("B","C","B"),column=c(2,2,10),assay=c("Assay1","Assay1","Assay1"),plate=c(1,1,1),stringsAsFactors=FALSE)
apply(a[1:2,],1,function(x) { all(x==a[1,]) })
apply(a[1:3,],1,function(x) { all(x==a[1,]) })
> > 1 2
 TRUE FALSE
> 1 2 3
FALSE FALSE FALSE
>

The second result is not right, it should be TRUE FALSE FALSE

Am I doing something wrong or is this a bug?  With other inputs it seems to 
work ok

Here is my sessionInfo()
> sessionInfo()
R version 3.2.5 (2016-04-14)
Platform: x86_64-redhat-linux-gnu (64-bit)
Running under: CentOS release 6.9 (Final)

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
>

Thank you,
Ramiro



Ramiro Barrantes Ph.D.
Precision Bioassay, Inc.
431 Pine St., Suite 110
Burlington, VT 05401
802 865 0155
802 861 2365 FAX
www.precisionbioassay.com
ram...@precisionbioassay.com

CONFIDENTIALITY NOTICE: This email, including any attach...{{dropped:9}}

__
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 extract individual values from varcomp?

2017-08-08 Thread Sharada Ramadass
Thanks! That helped. Was able to extract by character
Rgds,
Sharada

On Tue, Aug 8, 2017 at 8:20 PM, PIKAL Petr  wrote:
> Hi
>
> try
> str(varcompobject)
>
> to see structure of this object. You can extract parts by standard R means.
>
> Cheers
> Petr
>
>> -Original Message-
>> From: R-help [mailto:r-help-boun...@r-project.org] On Behalf Of Sharada
>> Ramadass
>> Sent: Tuesday, August 8, 2017 3:33 PM
>> To: r-help@r-project.org
>> Subject: [R] how to extract individual values from varcomp?
>>
>> Hello,
>>   I am trying to use varcomp to decompose the variance across multiple nested
>> levels on a lme object. I am able to successfully do this and when I view the
>> varcomp object I can see the individual values / estimates for the variance 
>> at
>> different levels.
>>
>> However, I want to be able to extract each of them separately, as I need to
>> build a confidence interval using bootstrapping on the sample data. How can I
>> go about extracting the individual estimates from varcomp object? The
>> datatype seems to show it as a double. Any pointers would be appreciated.
>>
>> Thanks and Regards,
>> Sharada
>>
>> __
>> 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.
>
> 
> Tento e-mail a jakékoliv k němu připojené dokumenty jsou důvěrné a jsou 
> určeny pouze jeho adresátům.
> Jestliže jste obdržel(a) tento e-mail omylem, informujte laskavě neprodleně 
> jeho odesílatele. Obsah tohoto emailu i s přílohami a jeho kopie vymažte ze 
> svého systému.
> Nejste-li zamýšleným adresátem tohoto emailu, nejste oprávněni tento email 
> jakkoliv užívat, rozšiřovat, kopírovat či zveřejňovat.
> Odesílatel e-mailu neodpovídá za eventuální škodu způsobenou modifikacemi či 
> zpožděním přenosu e-mailu.
>
> V případě, že je tento e-mail součástí obchodního jednání:
> - vyhrazuje si odesílatel právo ukončit kdykoliv jednání o uzavření smlouvy, 
> a to z jakéhokoliv důvodu i bez uvedení důvodu.
> - a obsahuje-li nabídku, je adresát oprávněn nabídku bezodkladně přijmout; 
> Odesílatel tohoto e-mailu (nabídky) vylučuje přijetí nabídky ze strany 
> příjemce s dodatkem či odchylkou.
> - trvá odesílatel na tom, že příslušná smlouva je uzavřena teprve výslovným 
> dosažením shody na všech jejích náležitostech.
> - odesílatel tohoto emailu informuje, že není oprávněn uzavírat za společnost 
> žádné smlouvy s výjimkou případů, kdy k tomu byl písemně zmocněn nebo písemně 
> pověřen a takové pověření nebo plná moc byly adresátovi tohoto emailu 
> případně osobě, kterou adresát zastupuje, předloženy nebo jejich existence je 
> adresátovi či osobě jím zastoupené známá.
>
> This e-mail and any documents attached to it may be confidential and are 
> intended only for its intended recipients.
> If you received this e-mail by mistake, please immediately inform its sender. 
> Delete the contents of this e-mail with all attachments and its copies from 
> your system.
> If you are not the intended recipient of this e-mail, you are not authorized 
> to use, disseminate, copy or disclose this e-mail in any manner.
> The sender of this e-mail shall not be liable for any possible damage caused 
> by modifications of the e-mail or by delay with transfer of the email.
>
> In case that this e-mail forms part of business dealings:
> - the sender reserves the right to end negotiations about entering into a 
> contract in any time, for any reason, and without stating any reasoning.
> - if the e-mail contains an offer, the recipient is entitled to immediately 
> accept such offer; The sender of this e-mail (offer) excludes any acceptance 
> of the offer on the part of the recipient containing any amendment or 
> variation.
> - the sender insists on that the respective contract is concluded only upon 
> an express mutual agreement on all its aspects.
> - the sender of this e-mail informs that he/she is not authorized to enter 
> into any contracts on behalf of the company except for cases in which he/she 
> is expressly authorized to do so in writing, and such authorization or power 
> of attorney is submitted to the recipient or the person represented by the 
> recipient, or the existence of such authorization is known to the recipient 
> of the person represented by the recipient.

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

[ESS] inferior-ess-own-frame

2017-08-08 Thread Benjamin Rogers
Hello,

I'm having a bit of a problem with my init.el file. When I installed ESS in 
windows 10, I installed a custom init.el file, which I have included as an 
attachment. The difficulty I'm having arises when I open R using C-c C-c, 
S-Enter, or any eval command. I'm used to having R start in a new frame with no 
other buffers, but it starts in a frame with a second buffer which contains my 
script. Any advice or help you might have would be appreciated.

Best,
Ben

Benjamin Rogers, Associate Auditor
Kansas Legislative Division of Post Audit
800 SW Jackson Street, Suite 1200
Topeka, KS, 66612
Ph.: 785 296-6482

__
ESS-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/ess-help


[R] Obtaining estimates and significance of random factors

2017-08-08 Thread Bharat Parthasarathy
0down votefavorite


I'm looking for way to obtain parameter estimates (such as *beta*, *SE* and
*t* scores) and *P* values of random factors after GLMM in R. My model
is:mod<-glmer(Boldness~Trial+(1|ID). The model with random effects is a
better model (lower loglikelihood, lower AIC and BIC) than the model
without random effects. Any help would be much appreciated. Thanks. Bharat

[[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] map_data

2017-08-08 Thread Jeff Newmiller
My guess is that you have either forgotten to load the package

library(maps)

or you have upgraded from R3.3 to R3.4, and such minor version changes lead to 
using a fresh package library and you need to (re-)install the maps package for 
the new version of R:

install.packages("maps")

so that the library function has access to it.

Before posting again,  please read the Posting Guide mentioned at the bottom of 
this message, and set your email program to send plain text email rather than 
HTML formatted email. That way, when you send code examples or the output of 
the sessionInfo function, we will see what you saw. 
-- 
Sent from my phone. Please excuse my brevity.

On August 8, 2017 4:36:12 AM PDT, "Полтораднев Максим Сергеевич" 
 wrote:
>Hello, I have some problems with calling the map_data function in maps
>package. Not so long ago it was not a problem, but for some reasons in
>July this year it became unavailable.
>
>For instance, if I call the following code:
>m<-map_data(“world”)
>The R returns to me:
>Error: cannot find function “map_data”
>
>Kind regards,
>Poltoradnev Maxim
>Head of products promotion division
>PJSC "Uralkali"
>Phone   +7-495-730-23-71
>Cell phone   +7-915-480-83-33
>www.uralkali.com
>
>
>
>ПАО «Уралкалий» - E-mail Дисклеймер
>
>Дисклеймер:
>Настоящее сообщение и любые прикрепленные к нему файлы (вместе
>именуемые «сообщение») предназначены исключительно для адресата.
>Настоящее сообщение может содержать конфиденциальную, частную и/или не
>подлежащую разглашению информацию. Любой несанкционированный просмотр,
>удержание, копирование, раскрытие или распространение данного сообщения
>строго запрещены.
>В случае, если Вы не являетесь адресатом данного сообщения, пожалуйста,
>удалите его и все его копии из Вашей системы, уничтожьте любые бумажные
>копии и сообщите отправителю посредством ответа. Вы не должны, прямо
>или косвенно, использовать, раскрывать, распространять, печатать,
>копировать, а также предпринимать какие-либо действия, полагаясь на
>данное сообщение, если Вы не являетесь его адресатом. Любые ошибки
>передачи данного сообщения не являются основаниями для отмены или
>утраты конфиденциальности или других средств правовой защиты.
>ПАО «Уралкалий» не несет ответственности за любые убытки или ущерб,
>возникшие в результате использования данного сообщения или от
>каких-либо вирусов, которые могут содержаться в прикрепленных к
>сообщению файлах и/или каком-либо указанном в сообщении Интернет сайте.
>ПАО «Уралкалий» не признаёт и не признает никакую претензию,
>требование, иск и/или обязательство в отношении любой сделки, договора
>или иного обязательства (в том числе, но не ограничиваясь, признанием
>задолженности или иного платежного требования), полностью или частично,
>если такое признание прямо или косвенно выражено в данном сообщении или
>в прикрепленных к сообщению файлах. Любое такое признание не может быть
>использовано в качестве аргумента и/или доказательства в суде,
>арбитраже или любом другом уполномоченном органе или организации до тех
>пор, пока не составлено в письменном виде и не подписано уполномоченным
>лицом со стороны ПАО «Уралкалий». Любая сделка, договор или иное
>обязательство должны быть оформлены в письменной форме. Никто не вправе
>заключать обязывающие сделки для ПАО «Уралкалий» путем обмена
>сообщениями, если такая сделка не подтверждена путем составления
>письменного документа, подписанного уполномоченным лицом со стороны ПАО
>«Уралкалий».
>
>Любые взгляды или мнения, изложенные в данном сообщении, принадлежат
>исключительно его автору и не обязательно отражают точку зрения ПАО
>«Уралкалий», если специально не указано иное.
>
>PJSC Uralkali - E-mail Disclaimer
>
>Disclaimer:
>This message and any files attached to it (together, the “e-mail”) are
>for the sole use of the intended recipient(s). This e-mail may contain
>confidential, proprietary and/or legally privileged information. Any
>unauthorized review, retention, duplication, disclosure, or
>distribution of this e-mail is strictly prohibited.
>If you are not the intended recipient of this e-mail, please delete it
>and all copies of it from your system, destroy any hard copies of it
>and notify the sender by reply e-mail. You must not, directly or
>indirectly, use, disclose, distribute, print, copy, or take any action
>in reliance on, any part of this e-mail if you are not the intended
>recipient. No confidentiality, privilege or other legal protection is
>waived or otherwise lost by any transmission errors related to this
>e-mail.
>PJSC Uralkali does not accept liability for any loss or damage
>resulting from the use of this e-mail or from any viruses that the
>files attached and/or any website linked to this e-mail may contain.
>
>PJSC Uralkali does not and will not admit any claim, demand, lawsuit
>and/or liability in relation to any transaction, agreement or other
>obligation (including but not limited to admission of 

Re: [R] Inheritance for S3 classes

2017-08-08 Thread Jeff Newmiller
The direct question seemed to be how to pass many optional parameters through, 
which seems obvious once you know it but the OP might not have seen it yet...

f1 <- function( x, y=1, z=2 ) {
  x*y + z
}

f2 <- function( x, ... ) {
  x <- x + 1
  f1( x, ... )
}

f2( 2, y=3 )

-- 
Sent from my phone. Please excuse my brevity.

On August 7, 2017 7:16:42 PM PDT, Bert Gunter  wrote:
>The S3 class model isn't really a class model. It's more a way of
>overloading functions. So it's rather simple, and there's less there
>than you might be expecting. I always thought the "Object Oriented
>Programming" chapter of the R language definition manual that ships
>with R was a very good treatment. Have you tried there? If not, please
>do so.
>
>But surely you know how to search! (e.g. "S3 class system in R") --
>there are many good tutorials on the internet. Also search at
>rseek.org, which is "optimized" for R queries.
>
>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 7, 2017 at 5:06 PM, Kym Nitschke 
>wrote:
>> Hi R Users,
>>
>> I am relatively new to programming in R … so I apologise if my
>questions appear ‘dumb’.
>>
>> I am using a package that defines a number of S3 classes. I want to
>create an S3 child class of one of these classes. The parent class has
>a contractor with many arguments. I have been having difficulty writing
>the child class contractor. I have been unable to find a good reference
>in the internet for writing S3 classes. What I have been able to find
>out so far is that the child class constructor should call the parent
>class constructor … which in this case requires passing the argument
>list with a variable number of arguments (i.e. there are a number of
>optional arguments) from the child to the parent.
>>
>> So my first question is … is there an easy way to do this? The
>match.call function will return a call object .. however the attributes
>function when used on the call object returns a ‘NULL’.
>>
>> My second question is … can any one recommend a good reference for
>object oriented programming in R which includes a comprehensive
>discussion of the S3 class model?
>>
>> Thanks
>>
>> Regards,
>>
>> Kym
>> __
>> 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] how to extract individual values from varcomp?

2017-08-08 Thread PIKAL Petr
Hi

try
str(varcompobject)

to see structure of this object. You can extract parts by standard R means.

Cheers
Petr

> -Original Message-
> From: R-help [mailto:r-help-boun...@r-project.org] On Behalf Of Sharada
> Ramadass
> Sent: Tuesday, August 8, 2017 3:33 PM
> To: r-help@r-project.org
> Subject: [R] how to extract individual values from varcomp?
>
> Hello,
>   I am trying to use varcomp to decompose the variance across multiple nested
> levels on a lme object. I am able to successfully do this and when I view the
> varcomp object I can see the individual values / estimates for the variance at
> different levels.
>
> However, I want to be able to extract each of them separately, as I need to
> build a confidence interval using bootstrapping on the sample data. How can I
> go about extracting the individual estimates from varcomp object? The
> datatype seems to show it as a double. Any pointers would be appreciated.
>
> Thanks and Regards,
> Sharada
>
> __
> 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.


Tento e-mail a jakékoliv k němu připojené dokumenty jsou důvěrné a jsou určeny 
pouze jeho adresátům.
Jestliže jste obdržel(a) tento e-mail omylem, informujte laskavě neprodleně 
jeho odesílatele. Obsah tohoto emailu i s přílohami a jeho kopie vymažte ze 
svého systému.
Nejste-li zamýšleným adresátem tohoto emailu, nejste oprávněni tento email 
jakkoliv užívat, rozšiřovat, kopírovat či zveřejňovat.
Odesílatel e-mailu neodpovídá za eventuální škodu způsobenou modifikacemi či 
zpožděním přenosu e-mailu.

V případě, že je tento e-mail součástí obchodního jednání:
- vyhrazuje si odesílatel právo ukončit kdykoliv jednání o uzavření smlouvy, a 
to z jakéhokoliv důvodu i bez uvedení důvodu.
- a obsahuje-li nabídku, je adresát oprávněn nabídku bezodkladně přijmout; 
Odesílatel tohoto e-mailu (nabídky) vylučuje přijetí nabídky ze strany příjemce 
s dodatkem či odchylkou.
- trvá odesílatel na tom, že příslušná smlouva je uzavřena teprve výslovným 
dosažením shody na všech jejích náležitostech.
- odesílatel tohoto emailu informuje, že není oprávněn uzavírat za společnost 
žádné smlouvy s výjimkou případů, kdy k tomu byl písemně zmocněn nebo písemně 
pověřen a takové pověření nebo plná moc byly adresátovi tohoto emailu případně 
osobě, kterou adresát zastupuje, předloženy nebo jejich existence je adresátovi 
či osobě jím zastoupené známá.

This e-mail and any documents attached to it may be confidential and are 
intended only for its intended recipients.
If you received this e-mail by mistake, please immediately inform its sender. 
Delete the contents of this e-mail with all attachments and its copies from 
your system.
If you are not the intended recipient of this e-mail, you are not authorized to 
use, disseminate, copy or disclose this e-mail in any manner.
The sender of this e-mail shall not be liable for any possible damage caused by 
modifications of the e-mail or by delay with transfer of the email.

In case that this e-mail forms part of business dealings:
- the sender reserves the right to end negotiations about entering into a 
contract in any time, for any reason, and without stating any reasoning.
- if the e-mail contains an offer, the recipient is entitled to immediately 
accept such offer; The sender of this e-mail (offer) excludes any acceptance of 
the offer on the part of the recipient containing any amendment or variation.
- the sender insists on that the respective contract is concluded only upon an 
express mutual agreement on all its aspects.
- the sender of this e-mail informs that he/she is not authorized to enter into 
any contracts on behalf of the company except for cases in which he/she is 
expressly authorized to do so in writing, and such authorization or power of 
attorney is submitted to the recipient or the person represented by the 
recipient, or the existence of such authorization is known to the recipient of 
the person represented by the recipient.
__
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] map_data

2017-08-08 Thread Полтораднев Максим Сергеевич
Hello, I have some problems with calling the map_data function in maps package. 
Not so long ago it was not a problem, but for some reasons in July this year it 
became unavailable.

For instance, if I call the following code:
m<-map_data(“world”)
The R returns to me:
Error: cannot find function “map_data”

Kind regards,
Poltoradnev Maxim
Head of products promotion division
PJSC "Uralkali"
Phone   +7-495-730-23-71
Cell phone   +7-915-480-83-33
www.uralkali.com



ПАО «Уралкалий» - E-mail Дисклеймер

Дисклеймер:
Настоящее сообщение и любые прикрепленные к нему файлы (вместе именуемые 
«сообщение») предназначены исключительно для адресата. Настоящее сообщение 
может содержать конфиденциальную, частную и/или не подлежащую разглашению 
информацию. Любой несанкционированный просмотр, удержание, копирование, 
раскрытие или распространение данного сообщения строго запрещены.
В случае, если Вы не являетесь адресатом данного сообщения, пожалуйста, удалите 
его и все его копии из Вашей системы, уничтожьте любые бумажные копии и 
сообщите отправителю посредством ответа. Вы не должны, прямо или косвенно, 
использовать, раскрывать, распространять, печатать, копировать, а также 
предпринимать какие-либо действия, полагаясь на данное сообщение, если Вы не 
являетесь его адресатом. Любые ошибки передачи данного сообщения не являются 
основаниями для отмены или утраты конфиденциальности или других средств 
правовой защиты.
ПАО «Уралкалий» не несет ответственности за любые убытки или ущерб, возникшие в 
результате использования данного сообщения или от каких-либо вирусов, которые 
могут содержаться в прикрепленных к сообщению файлах и/или каком-либо указанном 
в сообщении Интернет сайте.
ПАО «Уралкалий» не признаёт и не признает никакую претензию, требование, иск 
и/или обязательство в отношении любой сделки, договора или иного обязательства 
(в том числе, но не ограничиваясь, признанием задолженности или иного 
платежного требования), полностью или частично, если такое признание прямо или 
косвенно выражено в данном сообщении или в прикрепленных к сообщению файлах. 
Любое такое признание не может быть использовано в качестве аргумента и/или 
доказательства в суде, арбитраже или любом другом уполномоченном органе или 
организации до тех пор, пока не составлено в письменном виде и не подписано 
уполномоченным лицом со стороны ПАО «Уралкалий». Любая сделка, договор или иное 
обязательство должны быть оформлены в письменной форме. Никто не вправе 
заключать обязывающие сделки для ПАО «Уралкалий» путем обмена сообщениями, если 
такая сделка не подтверждена путем составления письменного документа, 
подписанного уполномоченным лицом со стороны ПАО «Уралкалий».

Любые взгляды или мнения, изложенные в данном сообщении, принадлежат 
исключительно его автору и не обязательно отражают точку зрения ПАО 
«Уралкалий», если специально не указано иное.

PJSC Uralkali - E-mail Disclaimer

Disclaimer:
This message and any files attached to it (together, the “e-mail”) are for the 
sole use of the intended recipient(s). This e-mail may contain confidential, 
proprietary and/or legally privileged information. Any unauthorized review, 
retention, duplication, disclosure, or distribution of this e-mail is strictly 
prohibited.
If you are not the intended recipient of this e-mail, please delete it and all 
copies of it from your system, destroy any hard copies of it and notify the 
sender by reply e-mail. You must not, directly or indirectly, use, disclose, 
distribute, print, copy, or take any action in reliance on, any part of this 
e-mail if you are not the intended recipient. No confidentiality, privilege or 
other legal protection is waived or otherwise lost by any transmission errors 
related to this e-mail.
PJSC Uralkali does not accept liability for any loss or damage resulting from 
the use of this e-mail or from any viruses that the files attached and/or any 
website linked to this e-mail may contain.

PJSC Uralkali does not and will not admit any claim, demand, lawsuit and/or 
liability in relation to any transaction, agreement or other obligation 
(including but not limited to admission of the indebtedness or other payment 
obligation), in full or in part, in case such admission, directly or indirectly 
is expressed in this e-mail or in any attachment to it. Any such admission may 
not be used as evidence and/or argument in court, arbitration or any other 
authority or organization, unless made in writing and signed by the legally 
authorized person on behalf of PJSC Uralkali. Any transaction, agreement or 
other obligation are subject to written contract. Nobody is authorized to 
conclude any binding agreement on behalf of PJSC Uralkali by e-mail unless and 
until such agreement is confirmed in writing and signed by the legally 
authorized person on behalf of PJSC Uralkali.
Any views or opinions expressed in this e-mail are solely those of the author 
and do not necessarily represent those of PJSC 

[R] how to extract individual values from varcomp?

2017-08-08 Thread Sharada Ramadass
Hello,
  I am trying to use varcomp to decompose the variance across multiple
nested levels on a lme object. I am able to successfully do this and
when I view the varcomp object I can see the individual values /
estimates for the variance at different levels.

However, I want to be able to extract each of them separately, as I
need to build a confidence interval using bootstrapping on the sample
data. How can I go about extracting the individual estimates from
varcomp object? The datatype seems to show it as a double. Any
pointers would be appreciated.

Thanks and Regards,
Sharada

__
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-es] unir varios archivos .csv en una serie historica

2017-08-08 Thread Sebastian Kruk
Hola Eric. Muchas gracias. Era exactamente lo que quería. Te agradezco mucho. 
Saludos, Sebastián.

Enviado desde Correo para Windows 10

De: eric
Enviado: martes, 8 de agosto de 2017 8:25
Para: Sebastian Kruk; Lista R
Asunto: Re: [R-es] unir varios archivos .csv en una serie historica

hola sebastian, invente 3 archivos con la estructura que describes y probe el 
codigo, le hice un par de arreglos necesarios, ahi va ... funciona bien con los 
archivos que te adjunto:
# usando la libreria data.table
library(data.table)
setwd("/tu/directorio/con/los/datos/")
filenames <- list.files(path = "/tu/directorio/con/los/datos/")
  # creas un data.table que contendra TODOS los datos de tus archivos
datos <- data.table()
  # ciclo para leer cada archivo
i<-1
for (i in 1:length(filenames))
    {
    # 1. leer los datos de un unico archivo
    data <- data.table()
    data <- fread(filenames[i], header=TRUE)
    # 2. transformar la estructura del archivo de filas con hora y columnas con 
dias a ( columna con dia, columna con hora y columna con precio )
      # primero usar stack() ... suponiendo que tu primera columna de datos es 
la hora del dia y tiene encabezado "horas"
    data.stacked <- data[,cbind(hora,stack(data, select=-hora))]
    data.stacked <- as.data.table(data.stacked)
    setnames(data.stacked,c("ind","values"),c("dia","precio"))
    # 3. agregar la columna con el nombre del mes
    data.stacked[, mes:=as.character(substr(filenames[i],1,3))]
    # 4. uniendo los datos
    datos <- rbind(datos,data.stacked)
    i <- i+1
    }
espero que te sirva,
suerte !!!
eric.



On 08/08/2017 06:50 AM, Sebastian Kruk wrote:
Hola Eric. Me diste una muy buena orientación.
Para algunos años los archivos son de excel donde cada uno tiene 12 hojas, una 
hoja por mes.
 
Cada hoja tiene el siguiente formato:
 
Hora 1 2 3 4 … 31
1 0 0 0 0 … 23
2 0 0 0 24 … 0
3 0 0 0 24,5 … 21
4 0 0 0 26 … 12
…
24 0 0 0 0 … 0
 
Por ejemplo en el día 1 el precio en las horas 1, 2, 3, 4 y 24 es 0, en cambio 
el día 31 el precio a la hora 1 es 23, a las 2 es 0, a las 3 es 21, a las 4 es 
12 y a las 24 es 0.
 
Espero no haberlos confundido más.
 
Gracias,
 
Sebastián.
 
Enviado desde mi teléfono con Windows 10
 
De: eric
Enviado: martes, 8 de agosto de 2017 6:52
Para: Sebastian Kruk; Lista R
Asunto: Re: [R-es] unir varios archivos .csv en una serie historica
 
Hola sebastian, sin el archivo de datos para probar y ver la estructura de los 
datos es un poco dificil, pero haciendo algunas suposiciones imagino que algo 
como esto te puede ayudar, seguro tendras que hacer ajustes:
# usando la libreria data.table
library(data.table)
filenames <- list.files(path = "/tu/path")
  # creas un data.table que contendra TODOS los datos de tus archivos
datos <- data.table()
  # ciclo para leer cada archivo
i<-1
for (i in 1:length(filenames))
    {
    # 0. crear un data.table para contener los datos de tu archivo de forma 
temporal dentro del ciclo
        data <- data.table()
    # 1. leer los datos de un unico archivo
    data <- as.data.table(fread(filenames[i], header=TRUE))
    
    # 2. transformar la estructura del archivo de filas con hora y columnas con 
dias a ( columna con dia, columna con hora y columna con precio )
      # primero usar stack() ... suponiendo que tu primera columna de datos es 
la hora del dia y tiene encabezado "horas"
    data.stacked <- data[,cbind(horas,stack(data, select=-horas))]
    data.stacked <- as.data.table(data.stacked)        
    
    # 3. agregar la columna con el nombre del mes
    data.stacked[, 
mes:=as.character(substr(filenames[i],posiciondelPRIMERcaracterdelnombredelmes,posiciondelULTIMOcaracterdelnombredelmes))]
    
    # 4. uniendo los datos
    datos <- rbind(datos,data)
    i <- i+1
    }
Ojala te sirva,
Suerte 
Eric.
 
 
 
On 08/07/2017 06:17 PM, Sebastian Kruk wrote:
Estimados usuarios-R:
 
Muy buenas noches.
 
Tengo una serie de archivos csv que contienen los precios mayoristas de
electricidad por hora.
 
Cada archivo csv corresponde a un mes de un cierto año.
 
Cada columna corresponde a un día del mes y cada fila a una hora del día (1
a 24 horas).
 
¿Hay alguna forma rápida de importar todos los datos y formar un vector
columna en que cada observación corresponde al precio que se dio en cierta
hora en cierto dia en cierto mes en cierto año?
 
Desde ya muchas gracias,
 
Sebastián.
 
  [[alternative HTML version deleted]]
 
___
R-help-es mailing list
R-help-es@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-help-es
 



-- 
Forest Engineer
Master in Environmental and Natural Resource Economics
Ph.D. student in Sciences of Natural Resources at La Frontera University
Member in AguaDeTemu2030, citizen movement for Temuco with green city standards 
for living
 
Nota: Las tildes se han omitido para asegurar compatibilidad con algunos 
lectores de correo.
 


-- 
Forest Engineer
Master in Environmental and Natural Resource 

Re: [R] Latin hypercube sampling from a non-uniform distribution

2017-08-08 Thread S Ellison
> However, my variable is simulated from the cumulative distribution function
> of the Poisson distribution. 
Then I am afraid I don't know what you're trying to achieve. 
Or why.

However, the principle holds; write a function that maps [0,1] to the 'pattern' 
you want, do that and apply it to the result from randomLHS. 
It happens that for generating data that follow a given probability 
distribution F, that function is the quantile function for F so you often do 
not need to write it.

 




***
This email and any attachments are confidential. Any use...{{dropped:8}}

__
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] Nested for loop

2017-08-08 Thread S Ellison
> The code I've attached works for a population of 400 and samples 100 times.
> I'd like to extend this to 300 samples and 3 populations. So, the x-axis would
> range from 0-300 samples.
> 
> What I'm having trouble with is finding a way to change the population mid-
> way through the function. I want samples 1-100 to be taken from a
> population of 400, samples 101-200 to be taken from a sample of 800 and
> samples 201-300 from a population of 300. The end result should look
> something like a heart rate monitor.

You could write your function to take a list of either subpopulations or sets 
of population parameters, lapply your simulation generator over the list and 
(assuming the output from each of those is a vector) use c(that.list, 
recursive=TRUE) to concatenate the resulting list of vectors into a single 
vector.


S Ellison


***
This email and any attachments are confidential. Any use...{{dropped:8}}

__
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-es] unir varios archivos .csv en una serie historica

2017-08-08 Thread eric

  
  
hola sebastian, invente 3 archivos con la estructura que
  describes y probe el codigo, le hice un par de arreglos
  necesarios, ahi va ... funciona bien con los archivos que te
  adjunto:

# usando la libreria data.table
  library(data.table)
  setwd("/tu/directorio/con/los/datos/")
  filenames <- list.files(path = "/tu/directorio/con/los/datos/")
    # creas un data.table que contendra TODOS los datos de tus
  archivos
  datos <- data.table()
    # ciclo para leer cada archivo
  i<-1
  for (i in 1:length(filenames))
      {
      # 1. leer los datos de un unico archivo
      data <- data.table()
      data <- fread(filenames[i], header=TRUE)
      # 2. transformar la estructura del archivo de filas con hora y
  columnas con dias a ( columna con dia, columna con hora y columna
  con precio )
        # primero usar stack() ... suponiendo que tu primera columna
  de datos es la hora del dia y tiene encabezado "horas"
      data.stacked <- data[,cbind(hora,stack(data,
  select=-hora))]
      data.stacked <- as.data.table(data.stacked)
      setnames(data.stacked,c("ind","values"),c("dia","precio"))
      # 3. agregar la columna con el nombre del mes
      data.stacked[, mes:=as.character(substr(filenames[i],1,3))]
      # 4. uniendo los datos
      datos <- rbind(datos,data.stacked)
      i <- i+1
      }
  

espero que te sirva,
suerte !!!
eric.






On 08/08/2017 06:50 AM, Sebastian Kruk
  wrote:


  
  
  
  
Hola Eric. Me diste una
muy buena orientación.
Para algunos años los
archivos son de excel donde cada uno tiene 12 hojas, una
hoja por mes.
 
Cada hoja tiene el
siguiente formato:
 
Hora 1 2 3 4 … 31
1 0 0 0 0 … 23
2 0 0 0 24 … 0
3 0 0 0 24,5 … 21
4 0 0 0 26 … 12
…
24 0 0 0 0 … 0
 
Por ejemplo en el día 1
el precio en las horas 1, 2, 3, 4 y 24 es 0, en cambio el
día 31 el precio a la hora 1 es 23, a las 2 es 0, a las 3 es
21, a las 4 es 12 y a las 24 es 0.
 
Espero no haberlos
confundido más.
 
Gracias,
 
Sebastián.
 
Enviado desde mi teléfono con Windows 10
 

  De: eric
Enviado: martes, 8 de agosto de 2017 6:52
Para: Sebastian Kruk; Lista R
Asunto: Re: [R-es] unir varios archivos .csv en una
serie historica

 
Hola sebastian, sin el archivo de datos para probar y ver la
  estructura de los datos es un poco dificil, pero haciendo
  algunas suposiciones imagino que algo como esto te puede
  ayudar, seguro tendras que hacer ajustes:
# usando la libreria data.table
  library(data.table)
  filenames <- list.files(path = "/tu/path")
    # creas un data.table que contendra TODOS los datos de tus
  archivos
  datos <- data.table()
    # ciclo para leer cada archivo
  i<-1
  for (i in 1:length(filenames))
      {
    # 0. crear un data.table para contener los datos de tu
  archivo de forma temporal dentro del ciclo
        data <- data.table()
    # 1. leer los datos de un unico archivo
      data <- as.data.table(fread(filenames[i], header=TRUE))
      
    # 2. transformar la estructura del archivo de filas con
  hora y columnas con dias a ( columna con dia, columna con hora
  y columna con precio )
        # primero usar stack() ... suponiendo que tu primera
  columna de datos es la hora del dia y tiene encabezado "horas"
      data.stacked <- data[,cbind(horas,stack(data,
  select=-horas))]
      data.stacked <- as.data.table(data.stacked)        
      
    # 3. agregar la columna con el nombre del mes
      data.stacked[,
mes:=as.character(substr(filenames[i],posiciondelPRIMERcaracterdelnombredelmes,posiciondelULTIMOcaracterdelnombredelmes))]
      
    # 4. uniendo los datos
      datos <- rbind(datos,data)
      i <- i+1
      }
Ojala te sirva,
Suerte 
Eric.
 
 
 

  On 08/07/2017 06:17 PM, Sebastian Kruk
wrote:


  Estimados usuarios-R:
   
  Muy buenas noches.
   
  Tengo una serie de archivos csv que contienen los precios mayoristas de
  electricidad por hora.
   
  Cada archivo csv corresponde a un mes de un cierto año.
   
  Cada columna 

Re: [R] Nested cross validation with lapply

2017-08-08 Thread Suzen, Mehmet
Hi Jesús,

Do you have a code you tried without lapply? Why don't you post that here too?

There are a couple of packages supporting nested CV; TANDEM, blkbox
you may want to check their code.

Also, `cvTools` package may help you to write one.

On 7 August 2017 at 15:21, Jesús Para Fernández
 wrote:
> Hi all!!
>
> How can i do nested cross validation with lapply??
>
> I know caret package, but I want to do it manuallly using lapply instead for 
> bucle.
>
> Thanks!!
> Jesús
>
> [[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-es] unir varios archivos .csv en una serie historica

2017-08-08 Thread Sebastian Kruk
Hola Eric. Me diste una muy buena orientación.
Para algunos años los archivos son de excel donde cada uno tiene 12 hojas, una 
hoja por mes.

Cada hoja tiene el siguiente formato:

Hora 1 2 3 4 … 31
1 0 0 0 0 … 23
2 0 0 0 24 … 0
3 0 0 0 24,5 … 21
4 0 0 0 26 … 12
…
24 0 0 0 0 … 0

Por ejemplo en el día 1 el precio en las horas 1, 2, 3, 4 y 24 es 0, en cambio 
el día 31 el precio a la hora 1 es 23, a las 2 es 0, a las 3 es 21, a las 4 es 
12 y a las 24 es 0.

Espero no haberlos confundido más.

Gracias,

Sebastián.

Enviado desde mi teléfono con Windows 10

De: eric
Enviado: martes, 8 de agosto de 2017 6:52
Para: Sebastian Kruk; Lista R
Asunto: Re: [R-es] unir varios archivos .csv en una serie historica

Hola sebastian, sin el archivo de datos para probar y ver la estructura de los 
datos es un poco dificil, pero haciendo algunas suposiciones imagino que algo 
como esto te puede ayudar, seguro tendras que hacer ajustes:
# usando la libreria data.table
library(data.table)
filenames <- list.files(path = "/tu/path")
  # creas un data.table que contendra TODOS los datos de tus archivos
datos <- data.table()
  # ciclo para leer cada archivo
i<-1
for (i in 1:length(filenames))
    {
    # 0. crear un data.table para contener los datos de tu archivo de forma 
temporal dentro del ciclo
        data <- data.table()
    # 1. leer los datos de un unico archivo
    data <- as.data.table(fread(filenames[i], header=TRUE))
    
    # 2. transformar la estructura del archivo de filas con hora y columnas con 
dias a ( columna con dia, columna con hora y columna con precio )
      # primero usar stack() ... suponiendo que tu primera columna de datos es 
la hora del dia y tiene encabezado "horas"
    data.stacked <- data[,cbind(horas,stack(data, select=-horas))]
    data.stacked <- as.data.table(data.stacked)        
    
    # 3. agregar la columna con el nombre del mes
    data.stacked[, 
mes:=as.character(substr(filenames[i],posiciondelPRIMERcaracterdelnombredelmes,posiciondelULTIMOcaracterdelnombredelmes))]
    
    # 4. uniendo los datos
    datos <- rbind(datos,data)
    i <- i+1
    }
Ojala te sirva,
Suerte 
Eric.



On 08/07/2017 06:17 PM, Sebastian Kruk wrote:
Estimados usuarios-R:

Muy buenas noches.

Tengo una serie de archivos csv que contienen los precios mayoristas de
electricidad por hora.

Cada archivo csv corresponde a un mes de un cierto año.

Cada columna corresponde a un día del mes y cada fila a una hora del día (1
a 24 horas).

¿Hay alguna forma rápida de importar todos los datos y formar un vector
columna en que cada observación corresponde al precio que se dio en cierta
hora en cierto dia en cierto mes en cierto año?

Desde ya muchas gracias,

Sebastián.

[[alternative HTML version deleted]]

___
R-help-es mailing list
R-help-es@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-help-es



-- 
Forest Engineer
Master in Environmental and Natural Resource Economics
Ph.D. student in Sciences of Natural Resources at La Frontera University
Member in AguaDeTemu2030, citizen movement for Temuco with green city standards 
for living

Nota: Las tildes se han omitido para asegurar compatibilidad con algunos 
lectores de correo.


[[alternative HTML version deleted]]

___
R-help-es mailing list
R-help-es@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-help-es

Re: [R-es] unir varios archivos .csv en una serie historica

2017-08-08 Thread eric

  
  
Hola sebastian, sin el archivo de datos para probar y ver la
  estructura de los datos es un poco dificil, pero haciendo algunas
  suposiciones imagino que algo como esto te puede ayudar, seguro
  tendras que hacer ajustes:
# usando la libreria data.table
  library(data.table)
  filenames <- list.files(path = "/tu/path")
    # creas un data.table que contendra TODOS los datos de tus
  archivos
  datos <- data.table()
    # ciclo para leer cada archivo
  i<-1
  for (i in 1:length(filenames))
      {
    # 0. crear un data.table para contener los datos de tu
  archivo de forma temporal dentro del ciclo

        data <- data.table()
    # 1. leer los datos de un unico archivo
      data <- as.data.table(fread(filenames[i], header=TRUE))
      

    # 2. transformar la estructura del archivo de filas con hora
  y columnas con dias a ( columna con dia, columna con hora y
  columna con precio )
        # primero usar stack() ... suponiendo que tu primera columna
  de datos es la hora del dia y tiene encabezado "horas"
      data.stacked <- data[,cbind(horas,stack(data,
  select=-horas))]
      data.stacked <- as.data.table(data.stacked)        
      

    # 3. agregar la columna con el nombre del mes
      data.stacked[,
mes:=as.character(substr(filenames[i],posiciondelPRIMERcaracterdelnombredelmes,posiciondelULTIMOcaracterdelnombredelmes))]
      

    # 4. uniendo los datos
      datos <- rbind(datos,data)
      i <- i+1
      }
  

Ojala te sirva,
Suerte 
Eric.






On 08/07/2017 06:17 PM, Sebastian Kruk
  wrote:


  Estimados usuarios-R:

Muy buenas noches.

Tengo una serie de archivos csv que contienen los precios mayoristas de
electricidad por hora.

Cada archivo csv corresponde a un mes de un cierto año.

Cada columna corresponde a un día del mes y cada fila a una hora del día (1
a 24 horas).

¿Hay alguna forma rápida de importar todos los datos y formar un vector
columna en que cada observación corresponde al precio que se dio en cierta
hora en cierto dia en cierto mes en cierto año?

Desde ya muchas gracias,

Sebastián.

	[[alternative HTML version deleted]]

___
R-help-es mailing list
R-help-es@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-help-es




-- 
Forest Engineer
Master in Environmental and Natural Resource Economics
Ph.D. student in Sciences of Natural Resources at La Frontera University
Member in AguaDeTemu2030, citizen movement for Temuco with green city standards for living

Nota: Las tildes se han omitido para asegurar compatibilidad con algunos lectores de correo.

  


___
R-help-es mailing list
R-help-es@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-help-es

[R] [R-pkgs] itunesr - new package to access iTunes App Store Ratings and Reviews

2017-08-08 Thread AMR RS
Hello Fellow Rusers,

Introducing '*itunesr' *my first package to help iOS Product Managers to
access Ratings and Reviews via R: https://cran.r-project.org/package=itunesr


Please give me suggestions to improve my next version

Would love contributions also!

https://github.com/amrrs/itunesr

https://cran.r-project.org/web/packages/itunesr/index.html

Thanks and Regards,
Abdul

[[alternative HTML version deleted]]

___
R-packages mailing list
r-packa...@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-packages

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