Re: [R] COXPH: How should weights be entered in coxph, as the log of the weight or as the weight on its original scale?

2021-05-19 Thread David Winsemius
Perhaps this package could be considered

https://cran.r-project.org/web/packages/hrIPW/hrIPW.pdf

That packages author also has a 2016 article in Statistics in Medicine on the 
properties of estimates from such analyses that might be useful. 

— 
David Winsemius, MD, MPH

Sent from my iPhone

> On May 19, 2021, at 8:01 PM, Sorkin, John  wrote:
> 
> When running a propensity score weighted analysis using coxph(), are the 
> weights entered as the log of the weights, or as the weights on the original 
> scale, i.e. coxph(Surv(time,status)~group,weights=weights   ,data=mydata) 
> or
>  coxph(Surv(time,status)~group,weights=log(weights),data=mydata)
> 
> I am creating weights using logistic regression as described below.
> 
> # Lalonde data from the MatchIt package is used in the pseudo code below
> install.packages("MatchIt")
> library("MatchIt")
> 
> #
> # Calculate propensity scores using logistic regression.#
> #
> ps <- glm(treat ~ age + educ +nodegree +re74+ 
> re75,data=lalonde,family=binomial())
> summary(ps)
> #PS on the scale of the dependent variable
> # Add the propensity scores to the dataset
> lalonde$psvalue <- predict(ps,type="response")
> #
> # END Calculate propensity scores using logistic regression.#
> #
> 
> #
> # Convert propensity scores to weights#
> #
> # Different weights for cases (1) and controls
> lalonde$weight.ATE <- ifelse(lalonde$treat == 1, 
> 1/lalonde$psvalue,1/(1-lalonde$psvalue))
> summary(lalonde$weight.ATE)
> #
> # END Convert propensity scores to weights#
> #
> 
> ##
> # Examples of two possible way  to enter weights in the coxph model. #
> ##
> fit1 <- coxph(Surv(time,status)~group,weights=lalonde$weight,data=lalonde)
> or
> fit2 <- 
> coxph(Surv(time,status)~group,weights=log(lalonde$weight),data=lalonde)
> ##
> # Examples of two possible way  to enter weights in the coxph model. #
> ##
> 
> 
>[[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.

[[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] COXPH: How should weights be entered in coxph, as the log of the weight or as the weight on its original scale?

2021-05-19 Thread Sorkin, John
When running a propensity score weighted analysis using coxph(), are the 
weights entered as the log of the weights, or as the weights on the original 
scale, i.e. coxph(Surv(time,status)~group,weights=weights   ,data=mydata) or
  coxph(Surv(time,status)~group,weights=log(weights),data=mydata)

I am creating weights using logistic regression as described below.

# Lalonde data from the MatchIt package is used in the pseudo code below
install.packages("MatchIt")
library("MatchIt")

#
# Calculate propensity scores using logistic regression.#
#
ps <- glm(treat ~ age + educ +nodegree +re74+ 
re75,data=lalonde,family=binomial())
summary(ps)
#PS on the scale of the dependent variable
# Add the propensity scores to the dataset
lalonde$psvalue <- predict(ps,type="response")
#
# END Calculate propensity scores using logistic regression.#
#

#
# Convert propensity scores to weights#
#
# Different weights for cases (1) and controls
lalonde$weight.ATE <- ifelse(lalonde$treat == 1, 
1/lalonde$psvalue,1/(1-lalonde$psvalue))
summary(lalonde$weight.ATE)
#
# END Convert propensity scores to weights#
#

##
# Examples of two possible way  to enter weights in the coxph model. #
##
fit1 <- coxph(Surv(time,status)~group,weights=lalonde$weight,data=lalonde)
or
fit2 <- coxph(Surv(time,status)~group,weights=log(lalonde$weight),data=lalonde)
##
# Examples of two possible way  to enter weights in the coxph model. #
##


[[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 in modifying code to extract data from url

2021-05-19 Thread Bhaskar Mitra
Hello Everyone,

I am trying to extract data from a url. The codes work well when the
data structure is as follows:

X Y
1 2
1 5
1 6
1 7
3 4

However, the code fails when the data structure has no number
under the 2nd column (shown below).I get the following error:

"Error in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 242, 241"


X Y
1 2
1
1
1 7
3 4

Can anyone please help me in how I can modify the codes ( shown below) to
adjust for the above mentioned condition
in the data structure.

library(rjson)

url <- "abcd.com"
json_data <- fromJSON(file= url)
d3 <- lapply(json_data[[2]], function(x) c(x["data"]))
d3 <- do.call(rbind, d3)
X_Dataframe = as.data.frame(unlist(d3[[1]]))
b <- do.call("cbind", split(X_Dataframe, rep(c(1, 2), length.out =
nrow(X_Dataframe


regards,
bhaskar

[[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-es] random forest y datos faltantes

2021-05-19 Thread Eric Concha M.


Hoal Carlos, muchas gracias por compartir tu experiencia.

Slds,

Eric.



On Wed, 19 May 2021 12:01:29 +0200
Carlos Ortega  wrote:

> Hola Eric,
> 
> La función "pool()" es una modificación de las funciones "tidy()" y
> "glance()" del paquete "broom" y permite extraer y presentar de forma
> muy amigable resultados de un modelo.
> El paquete "broom" incluye la posibilidad de extraer parámetros,
> coeficientes, valores de bondad de ajuste, etc de múltiples modelos
> de R. El paquete "mice" lo que hace es utilizar esta función para
> presentarte resultados del modelo ajustado de forma muy equivalente a
> lo que hacen las funciones de "broom".
> 
> En tu caso, simplemente imputa tus NAs con los paquetes "missForest"
> (te recomiendo muy especialmente otra alternativa con "missRanger") o
> cualquier otro, y sobre el conjunto imputado tendrás que definir un
> modelo ("lm", "glm"... lo que consideres) y sobre el modelo ajustado
> usa la función "tidy()" o "glance(), tendrás que haber incluido la
> librería "broom" previamente. Y tendrás tus resultados como en "mice".
> 
> Mira el ejemplo de la salida que producen las funciones "tidy()" y
> "glance()" del paquete "broom" para que veas que el resultado es
> equivalente al que produce "pool()"
> 
> > library(ggplot2)
> > library(dplyr)
> >
> > mod <- lm(mpg ~ wt + qsec, data = mtcars)
> >
> > tidy(mod)
> # A tibble: 3 x 5
>   termestimate std.error statistic  p.value
>   
> 1 (Intercept)   19.7   5.25   3.76 7.65e- 4
> 2 wt-5.05  0.484-10.4  2.52e-11
> 3 qsec   0.929 0.265  3.51 1.50e- 3
> > glance(mod)
> # A tibble: 1 x 12
>   r.squared adj.r.squared sigma statistic  p.valuedf logLik   AIC
>   BIC deviance df.residual  nobs
>  
>  
> 1 0.826 0.814  2.60  69.0 9.39e-12 2  -74.4  157.
>  163. 195.  2932
> >
> 
> 
> Saludos,
> Carlos Ortega
> www.qualityexcellence.es
> 
> 
> 
> El mié, 19 may 2021 a las 4:40, Eric Concha M.
> () escribió:
> 
> >
> > Hola chicos, una pregunta por favor, quizá alguien sabe ... tengo un
> > set de datos con missings y no lo puedo imputar con MICE, pero sí
> > con missForest. Mi problema es que MICE hace todo el trabajo de
> > calcular los parámetros del modelo de interés bajo el set de datos
> > imputados, las nuevas varianza, grados de libertad y así, con la
> > función pool() se obtienen esa información.
> >
> > Mi pregunta es: hay algo parecido a pool() de MICE para alguno de
> > los algoritmos que usan random forest como missforest o
> > missCompare, por ejemplo ? missforest hace un gran trabajo
> > obteniendo los datos faltantes, pero de lo que leí desde su viñeta,
> > no va más allá ... llevo buscando desde ayer, pero me ha ido mal.
> >
> > No quiero hacer el trabajo a mano pues me va a llevar mucho tiempo,
> > nosoy muy experto y tengo una alta probabilidad de equivocarme.
> >
> > Espero haber explicado bien mi necesidad.
> >
> > Saludos y gracias !!
> >
> > Eric.
> >
> > ___
> > R-help-es mailing list
> > R-help-es@r-project.org
> > https://stat.ethz.ch/mailman/listinfo/r-help-es
> >
> 
> 

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


Re: [R] Plot with some countries in red

2021-05-19 Thread PIKAL Petr
Hi

For your example

sel <- c(1,4, 9, 11)
text(B, C, A, col=  c("black", "red")[(A %in% A[sel])+1])

gives you required colouring.Not sure if it works with basicPlotteR.

Cheers
Petr

-Original Message-
From: R-help  On Behalf Of varin sacha via R-help
Sent: Wednesday, May 19, 2021 3:14 PM
To: r-help@r-project.org
Subject: [R] Plot with some countries in red

Dear R-experts,

Here below a toy R code example. I would like some countries (not all of them) 
"Italy", "Canada", "Greece" and "Norway" to appear in red color. The others 
remaining black. How can I do that without big changes in my R code ? Indeed, I 
would like my R code to remain like this as much as possible, for example, end 
of my R code, I want to keep the non-overlapping text label.


A<-c("Italy","Germany","USA","Canada","Turkey","Chile","Mexico","Japan","Norway","Finland","Greece")
B<-c(540,523,589,600,499,567,485,467,543,511,500)
C<-c(470,470,489,492,476,475,455,444,489,456,478)

mod1=loess(C~B,span=0.7)
Bfit=seq(from=min(C),to=max(C),length.out=100)
Afit1=predict(mod1,newdata=Bfit)
plot(B,C,main="Courbe de régression non paramétrique entre ISQ 2015 et ISQ 
2018", xlab="score ISQ 2015", ylab="score ISQ 2018 ",type="n")
points(Bfit,Afit1,type="l",lwd=2,col="red")

library(basicPlotteR)
# Add non-overlapping text labels
addTextLabels(B, C, A, col.label="black")








__
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.
Osobní údaje: Informace o zpracování a ochraně osobních údajů obchodních 
partnerů PRECHEZA a.s. jsou zveřejněny na: 
https://www.precheza.cz/zasady-ochrany-osobnich-udaju/ | Information about 
processing and protection of business partner’s personal data are available on 
website: https://www.precheza.cz/en/personal-data-protection-principles/
Důvěrnost: Tento e-mail a jakékoliv k němu připojené dokumenty jsou důvěrné a 
podléhají tomuto právně závaznému prohláąení o vyloučení odpovědnosti: 
https://www.precheza.cz/01-dovetek/ | This email and any documents attached to 
it may be confidential and are subject to the legally binding disclaimer: 
https://www.precheza.cz/en/01-disclaimer/

__
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] Plot with some countries in red

2021-05-19 Thread varin sacha via R-help
Dear R-experts,

Here below a toy R code example. I would like some countries (not all of them) 
"Italy", "Canada", "Greece" and "Norway" to appear in red color. The others 
remaining black. How can I do that without big changes in my R code ? Indeed, I 
would like my R code to remain like this as much as possible, for example, end 
of my R code, I want to keep the non-overlapping text label.


A<-c("Italy","Germany","USA","Canada","Turkey","Chile","Mexico","Japan","Norway","Finland","Greece")
B<-c(540,523,589,600,499,567,485,467,543,511,500)
C<-c(470,470,489,492,476,475,455,444,489,456,478)

mod1=loess(C~B,span=0.7)
Bfit=seq(from=min(C),to=max(C),length.out=100)
Afit1=predict(mod1,newdata=Bfit)
plot(B,C,main="Courbe de régression non paramétrique entre ISQ 2015 et ISQ 
2018", xlab="score ISQ 2015", ylab="score ISQ 2018 ",type="n")
points(Bfit,Afit1,type="l",lwd=2,col="red")

library(basicPlotteR) 
# Add non-overlapping text labels
addTextLabels(B, C, A, col.label="black")  


 

 

 

__
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-es] BioStatFLOSS y EpiLinux

2021-05-19 Thread miguel.angel.rodriguez.muinos
Hola.


Retomando este antiguo hilo, os anuncio la reciente publicaci�n de:


- BioStatfloss V5.0: https://www.sergas.es/Saude-publica/BioStatFLOSS?idioma=es?


- EpiLinux v6.0: https://www.sergas.es/Saude-publica/Epilinux?idioma=es



Notas (un poco al azar):


- Obviamente, R es una de las aplicaciones principales (junto con RCommander y 
RStudio como interfaces gr�ficas) en ambos proyectos.


- A los usuarios de Windows (BioStatFLOSS), os recomiendo que le ech�is un ojo 
a Radiant (otro GUI de R basado web -con Shiny-) y como proyectos derivados de 
R: JASP y Jamovi.


- Todas las aplicaciones de BioStatFLOSS son portables (no necesitan 
instalaci�n) e independientes unas de otras, por lo que se puede copiar la 
carpeta correspondiente y ejecutar por separado desde un pendrive, HD externo o 
en el propio equipo.


- La ISO de EpiLinux se puede probar desde una m�quina virtual o grab�ndola en 
un pendrive (con Rufus o Etcher, por ejemplo); en este caso, una vez grabado el 
pendrive o HD externo, hay que indicarle al equipo que arranque desde �l.


- Tanto en BioStatFLOSS como en EpiLinux se incluye Epidat (otro de nuestros 
proyectos de software). M�s info: 
https://www.sergas.es/Saude-publica/EPIDAT?idioma=es



Espero que a alguien el resulte de utilidad.

Un saludo,

-

Miguel �ngel Rodr�guez Mu��os

Direcci�n Xeral de Sa�de P�blica

Conseller�a de Sanidade

Xunta de Galicia

https://dxsp.sergas.gal/




[R-es] EpiLinux 5
miguel.angel.rodriguez.muinos en sergas.es miguel.angel.rodriguez.muinos en 
sergas.es
Lun Ene 22 09:21:46 CET 2018


Hola.


Os anuncio la publicaci�n de la versi�n 5 de EpiLinux.


Es una distribuci�n cient�fica de Linux, basada en Ubuntu de 64 bits con 
entorno de escritorio LXDE, que incluye una recopilaci�n de software 
espec�ficamente orientado al an�lisis de datos, la bioestad�stica y/o la 
epidemiolog�a.


Obviamente, el "n�cleo central" de la distro es R (que viene con tres entornos 
gr�ficos preinstalados: RCommander, RKward y RStudio) aunque la selecci�n de 
software es amplia.


Ten�is m�s informaci�n aqu� -> 
https://www.sergas.es/Saude-publica/Epilinux?idioma=es


Se puede descargar en forma de ISO (4Gb aprox.). Esta ISO se puede montar 
virtualizada o pasarla a un pendrive para convertirla en una distribuci�n live 
-funciona aut�nomamente desde el propio pendrive-. Tambi�n se puede instalar en 
el disco duro del ordenador.


Espero que os pueda ser �til. Aunque es dif�cil que alguien de esta lista no 
tenga ya un entorno de trabajo estable y personalizado, este tipo de 
distribuciones "live" son bastante adecuadas para la formaci�n por no ser 
agresivas con el sistema operativo host del ordenador y/o para iniciarse en 
este campo (nota: para este prop�sito os recomiendo que prob�is JASP, a los que 
no lo conoc�is)


Si ten�is alg�n ordenador por ah� que ya no puede con las nuevas versiones de 
Windows, pod�is probarla tambi�n (mejor instalada en el HD porque ese tipo de 
equipos suele tener puertos USB "lentos"), igual os sorprende su ligereza.


Se agradecen comentarios, sugerencias, ideas, cr�ticas, 


Un saludo,
Miguel.











Nota: A informaci�n contida nesta mensaxe e os seus posibles documentos 
adxuntos � privada e confidencial e est� dirixida �nicamente � seu 
destinatario/a. Se vostede non � o/a destinatario/a orixinal desta mensaxe, por 
favor elim�nea. A distribuci�n ou copia desta mensaxe non est� autorizada.

Nota: La informaci�n contenida en este mensaje y sus posibles documentos 
adjuntos es privada y confidencial y est� dirigida �nicamente a su 
destinatario/a. Si usted no es el/la destinatario/a original de este mensaje, 
por favor elim�nelo. La distribuci�n o copia de este mensaje no est� autorizada.

See more languages: http://www.sergas.es/aviso-confidencialidad

[[alternative HTML version deleted]]

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