Re: [R] implicit loop for nested list

2023-01-27 Thread Naresh Gurbuxani
Thanks everyone for their solutions.  My problem is solved.

Sent from my iPhone

> On Jan 27, 2023, at 12:17 AM, Andrew Simmons  wrote:
> 
> I would use replicate() to do an operation with random numbers repeatedly:
> 
> ```
> mysim <- replicate(10, {
>two.mat <- matrix(rnorm(4), 2, 2)
>four.mat <- matrix(rnorm(16), 4, 4)
>list(two.mat = two.mat, four.mat = four.mat)
> })
> ```
> 
> which should give you a matrix-list. You can slice this matrix-list
> just like normal, then cbind it in one step:
> 
> ```
> two.mat <- do.call("cbind", mysim["two.mat", ])
> four.mat <- do.call("cbind", mysim["four.mat", ])
> ```
> 
>> On Thu, Jan 26, 2023 at 10:33 PM Naresh Gurbuxani
>>  wrote:
>> 
>>> 
>>> I am looking for a more elegant way to write below code.
>>> 
>>> #Simulation results have different dimensions
>>> mysim <- lapply(1:10, function(y) {
>>>   two.mat <- matrix(rnorm(4), nrow = 2)
>>>   four.mat <- matrix(rnorm(16), nrow = 4)
>>>   list(two.mat = two.mat, four.mat = four.mat) #results with different 
>>> dimensions
>>> })
>>> 
>>> #Collect different components of simulation results
>>> #Is it possible to do this with implicit loops?
>>> mat2 <- matrix(nrow = 2, ncol = 1)
>>> mat4 <- matrix(nrow = 4, ncol = 1)
>>> for (mat.list in mysim) {
>>>   mat2 <- cbind(mat2, mat.list[["two.mat"]])
>>>   mat4 <- cbind(mat4, mat.list[["four.mat"]])
>>> }
>>> mat2 <- mat2[,-1]
>>> mat4 <- mat4[,-1]
>> 
>> __
>> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
__
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] implicit loop for nested list

2023-01-26 Thread Andrew Simmons
I would use replicate() to do an operation with random numbers repeatedly:

```
mysim <- replicate(10, {
two.mat <- matrix(rnorm(4), 2, 2)
four.mat <- matrix(rnorm(16), 4, 4)
list(two.mat = two.mat, four.mat = four.mat)
})
```

which should give you a matrix-list. You can slice this matrix-list
just like normal, then cbind it in one step:

```
two.mat <- do.call("cbind", mysim["two.mat", ])
four.mat <- do.call("cbind", mysim["four.mat", ])
```

On Thu, Jan 26, 2023 at 10:33 PM Naresh Gurbuxani
 wrote:
>
> >
> > I am looking for a more elegant way to write below code.
> >
> > #Simulation results have different dimensions
> > mysim <- lapply(1:10, function(y) {
> >two.mat <- matrix(rnorm(4), nrow = 2)
> >four.mat <- matrix(rnorm(16), nrow = 4)
> >list(two.mat = two.mat, four.mat = four.mat) #results with different 
> > dimensions
> > })
> >
> > #Collect different components of simulation results
> > #Is it possible to do this with implicit loops?
> > mat2 <- matrix(nrow = 2, ncol = 1)
> > mat4 <- matrix(nrow = 4, ncol = 1)
> > for (mat.list in mysim) {
> >mat2 <- cbind(mat2, mat.list[["two.mat"]])
> >mat4 <- cbind(mat4, mat.list[["four.mat"]])
> > }
> > mat2 <- mat2[,-1]
> > mat4 <- mat4[,-1]
>
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

__
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] implicit loop for nested list

2023-01-26 Thread Jeff Newmiller
Elegance is in the eyes of the beholder...

extractor <- function( simlist, sim_name ) {
  do.call(
cbind
  , lapply(
  simlist
, function( r ) r[[ sim_name ]]
)
  )
}
extractor( mysim, "two.mat" )

... but using do.call will be much more memory efficient than successive cbind 
operations.


On January 26, 2023 7:33:25 PM PST, Naresh Gurbuxani 
 wrote:
>> 
>> I am looking for a more elegant way to write below code.
>> 
>> #Simulation results have different dimensions
>> mysim <- lapply(1:10, function(y) {
>>two.mat <- matrix(rnorm(4), nrow = 2)
>>four.mat <- matrix(rnorm(16), nrow = 4)
>>list(two.mat = two.mat, four.mat = four.mat) #results with different 
>> dimensions
>> })
>> 
>> #Collect different components of simulation results
>> #Is it possible to do this with implicit loops?
>> mat2 <- matrix(nrow = 2, ncol = 1)
>> mat4 <- matrix(nrow = 4, ncol = 1)
>> for (mat.list in mysim) {
>>mat2 <- cbind(mat2, mat.list[["two.mat"]])
>>mat4 <- cbind(mat4, mat.list[["four.mat"]])
>> }
>> mat2 <- mat2[,-1]
>> mat4 <- mat4[,-1]
>
>__
>R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.

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

__
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] implicit loop for nested list

2023-01-26 Thread Bert Gunter
Is this what you want:

## This cbinds all the 2 matrix components of mysim
## producing a 2 x 20 matrix
do.call(cbind,lapply(mysim,`[[`,1))

## Change the 1 to a 2 to cbind the other components.

Cheers,
Bert

Tha

On Thu, Jan 26, 2023 at 7:33 PM Naresh Gurbuxani <
naresh_gurbux...@hotmail.com> wrote:

> >
> > I am looking for a more elegant way to write below code.
> >
> > #Simulation results have different dimensions
> > mysim <- lapply(1:10, function(y) {
> >two.mat <- matrix(rnorm(4), nrow = 2)
> >four.mat <- matrix(rnorm(16), nrow = 4)
> >list(two.mat = two.mat, four.mat = four.mat) #results with different
> dimensions
> > })
> >
> > #Collect different components of simulation results
> > #Is it possible to do this with implicit loops?
> > mat2 <- matrix(nrow = 2, ncol = 1)
> > mat4 <- matrix(nrow = 4, ncol = 1)
> > for (mat.list in mysim) {
> >mat2 <- cbind(mat2, mat.list[["two.mat"]])
> >mat4 <- cbind(mat4, mat.list[["four.mat"]])
> > }
> > mat2 <- mat2[,-1]
> > mat4 <- mat4[,-1]
>
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

[[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] implicit loop for nested list

2023-01-26 Thread Naresh Gurbuxani
> 
> I am looking for a more elegant way to write below code.
> 
> #Simulation results have different dimensions
> mysim <- lapply(1:10, function(y) {
>two.mat <- matrix(rnorm(4), nrow = 2)
>four.mat <- matrix(rnorm(16), nrow = 4)
>list(two.mat = two.mat, four.mat = four.mat) #results with different 
> dimensions
> })
> 
> #Collect different components of simulation results
> #Is it possible to do this with implicit loops?
> mat2 <- matrix(nrow = 2, ncol = 1)
> mat4 <- matrix(nrow = 4, ncol = 1)
> for (mat.list in mysim) {
>mat2 <- cbind(mat2, mat.list[["two.mat"]])
>mat4 <- cbind(mat4, mat.list[["four.mat"]])
> }
> mat2 <- mat2[,-1]
> mat4 <- mat4[,-1]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R-es] Loop para sumar

2022-11-25 Thread Marcelino de la Cruz Rot

Buenas tardes:

seq(from=169631.4, to=568497.6, by=250)

Saludos,
Marcelino


El 25/11/2022 a las 13:03, Yesica Pallavicini Fernandez escribió:

[No suele recibir correo electrónico de yesipa...@gmail.com. Descubra por qué 
esto es importante en https://aka.ms/LearnAboutSenderIdentification ]

Buenos días.
Necesito dividir un mapa en celdas de 250m.
Tengo la UTM de partida y la de Llegada.

El comando que quisiera elaborar sería:
Desde este punto de partida, suma 250m y el posterior a 250m desde el punto
anterior y asi sucesivamente hasta llegar al punto de llegada. Solo voy a
utilizar la UTM X.
Y quisiera crear un vector que contenga todos esos puntos.
¿Me explico bien?
169631.4
568497.6
¿R puede aguantar mas de un millón quinientosmil datos que va a tener ese
vector?
Este es mi intento, pero me falta decirle que sume los 250 al punto
anterior.

datos=for(for(i in  169631.4: 568497.6  ){
  print(i^2)
}

Muchas gracias

Yésica

 [[alternative HTML version deleted]]

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



--
Marcelino de la Cruz Rot
Coordinador funcional de Biología
Depto. de Biología y Geología
Física y Química Inorgánica
Universidad Rey Juan Carlos
Móstoles España

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


[R-es] loop para sumar una constante

2022-11-25 Thread Yesica Pallavicini Fernandez
Hola.
En el mensaje anterior no he expresado correctamente lo que quiero.
A ver si ahora me explico mejor.

Tengo de partida un valor; por ejemplo 1
A ese 1 quiero sumarle 5 y luego al punto anterior quiero sumar otros 5 más
y así hasta llegar a 30.
El primer punto sería 6, el segundo 6+5=11, el siguiente 11+5= 16 y
así sucesivamente hasta llegar a 30.
Es decir que necesito que me devuelva como resultado
1, 6,11,16,21,26

Gracias por vuestra ayuda

Yésica

[[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] Loop para sumar

2022-11-25 Thread Reverté Calvet , Gerard via R-help-es
No acabo de entender muy bien lo que necesitas Y�sica. Mirate si esto te sirve


x <- 169631.4

vector <- vector()
while(x < 568497.6){
  vector <- c(vector,x)
  x <- x + 250
}




Gerard




De: R-help-es  de part de Yesica Pallavicini 
Fernandez 
Enviat el: divendres, 25 de novembre de 2022 13:03
Per a: Lista R
Tema: [R-es] Loop para sumar

Buenos d�as.
Necesito dividir un mapa en celdas de 250m.
Tengo la UTM de partida y la de Llegada.

El comando que quisiera elaborar ser�a:
Desde este punto de partida, suma 250m y el posterior a 250m desde el punto
anterior y asi sucesivamente hasta llegar al punto de llegada. Solo voy a
utilizar la UTM X.
Y quisiera crear un vector que contenga todos esos puntos.
�Me explico bien?
169631.4
568497.6
�R puede aguantar mas de un mill�n quinientosmil datos que va a tener ese
vector?
Este es mi intento, pero me falta decirle que sume los 250 al punto
anterior.

datos=for(for(i in  169631.4: 568497.6  ){
 print(i^2)
}

Muchas gracias

Y�sica

[[alternative HTML version deleted]]

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

Av�s legal/Aviso legal

La present informaci� s'envia �nicament a la persona a la que va dirigida i pot 
contenir informaci� privilegiada o de car�cter confidencial. Qualsevol 
modificaci�, retransmissi�, difusi� o altre �s d'aquesta informaci� per 
persones o entitats diferents a la persona a la que va dirigida est� prohibida. 
Si vost� l'ha rebut per error, si us plau contacti amb el remitent i esborri el 
missatge de qualsevol ordinador. En el cas que aquest missatge vagi a ser 
contestat per la mateixa via, ha de saber-se que la seva resposta podria ser 
coneguda per tercers a l'entrar a la xarxa. Per aix�, si el missatge inclou 
contrasenyes, n�meros de targetes de cr�dit o qualsevol altra informaci� que 
vost� consideri confidencial, seria m�s segur contestar per una altra via i 
cancel�lar la seva transmissi�. L'Ajuntament de Matar� i els seus organismes 
dependents no poden assumir la responsabilitat derivada del fet de qu� terceres 
persones puguin arribar a con�ixer el contingut d'aquest missatge durant la 
seva transmissi�.

La presente informaci�n se env�a �nicamente a la persona a la que va dirigida y 
puede contener informaci�n privilegiada o de car�cter confidencial. Cualquier 
modificaci�n, retransmisi�n, difusi�n u otro uso de esta informaci�n por 
persones o entidades diferentes a la persona a la que va dirigida est� 
prohibida. Si usted la ha recibido por error, por favor contacte con el 
remitente y borre el mensaje. En el caso de que este mensaje vaya a ser 
contestado por la misma v�a, ha de saberse que su respuesta podr�a ser conocida 
por terceros al entrar en la red. Por este motivo, si el mensaje incluye 
contrase�as, n�meros de tarjetas de cr�dito o cualquier otra informaci�n que 
considere confidencial, ser�a m�s seguro contestar por otra v�a y cancelar su 
transmisi�n. El Ayuntamiento de Matar� y sus organismos dependientes no pueden 
asumir la responsabilidad derivada del hecho de que terceras personas puedan 
llegar a conocer el contenido de este mensaje durante su transmisi�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


[R-es] Loop para sumar

2022-11-25 Thread Yesica Pallavicini Fernandez
Buenos días.
Necesito dividir un mapa en celdas de 250m.
Tengo la UTM de partida y la de Llegada.

El comando que quisiera elaborar sería:
Desde este punto de partida, suma 250m y el posterior a 250m desde el punto
anterior y asi sucesivamente hasta llegar al punto de llegada. Solo voy a
utilizar la UTM X.
Y quisiera crear un vector que contenga todos esos puntos.
¿Me explico bien?
169631.4
568497.6
¿R puede aguantar mas de un millón quinientosmil datos que va a tener ese
vector?
Este es mi intento, pero me falta decirle que sume los 250 al punto
anterior.

datos=for(for(i in  169631.4: 568497.6  ){
 print(i^2)
}

Muchas gracias

Yésica

[[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] for loop question in R

2021-12-22 Thread Kai Yang via R-help
 Hi Rui and Ivan,Thank you explain of the code for me in detail. This is very 
helpful. And the code works well now.Happy Holiday,Kai
On Wednesday, December 22, 2021, 02:30:49 PM PST, Rui Barradas 
 wrote:  
 
 Hello,

y[i] and c[i] are character strings, they are not variables of data set mpg.
To get the variables, use, well, help("get").

Note that I have changed the temp dir to mine. So I created a variable 
to hold the value


tmpdir <- "c:/temp/"

for (i in seq(nrow(mac))){
  mpg %>%
    filter(hwy < 35) %>%
    ggplot(aes(x = displ, y = get(y[i]), color = get(c[i]))) +
    geom_point() +
    ylab(y[i]) +
    guides(color = guide_legend(title = c[i]))
  ggsave(
    paste0(tmpdir, f[i], ".jpg"),
    width = 9,
    height = 6,
    dpi = 1200,
    units = "in")
}



Like Ivan said, don't rely on auto print. In order to have to open the 
graphics files output by the loop I would have done something like the 
following.

First create a list to hold the plots. Inside the for loop save the 
plots in the list and explicitly print them. And use ggsave argument 
plot. Like this, after the loop you can see what you have by printing 
each list member.


p <- vector("list", length = nrow(mac))
for (i in seq(nrow(mac))){
  mpg %>%
    filter(hwy < 35) %>%
    ggplot(aes(x = displ, y = get(y[i]), color = get(c[i]))) +
    geom_point() +
    ylab(y[i]) +
    guides(color = guide_legend(title = c[i])) -> p[[i]]
  ggsave(
    paste0(tmpdir, f[i], ".jpg"),
    plot = p[[i]],
    width = 9,
    height = 6,
    dpi = 1200,
    units = "in")
}

# See the first plot
p[[1]]


Hope this helps,

Rui Barradas

Às 18:18 de 22/12/21, Kai Yang via R-help escreveu:
>  Hello Eric, Jim and Ivan,
> Many thanks all of your help. I'm a new one in R area. I may not fully 
> understand the idea from you.  I modified my code below, I can get the plots 
> out with correct file name, but plots  are not using correct fields' name. it 
> use y[i], and c[i] as variables' name, does not use hwy, cyl or cty, class in 
> ggplot statement. And there is not any error message. Could you please look 
> into my modified code below and let me know how to modify y= y[i], color = 
> c[i] part?
> Thanks,
> Kai
> 
> y <- c("hwy","cty")
> c <- c("cyl","class")
> f <- c("hwy_cyl","cty_class")
> mac <- data.frame(y,c,f)
> for (i in seq(nrow(mac))){
>    mpg %>%
>      filter(hwy <35) %>%
>      ggplot(aes(x = displ, y = y[i], color = c[i])) +
>      geom_point()
>    ggsave(paste0("c:/temp/",f[i],".jpg"),width = 9, height = 6, dpi = 1200, 
>units = "in")
> }
> 
>      On Wednesday, December 22, 2021, 09:42:45 AM PST, Ivan Krylov 
> wrote:
>  
>  On Wed, 22 Dec 2021 16:58:18 + (UTC)
> Kai Yang via R-help  wrote:
> 
>> mpg %>%    filter(hwy <35) %>%     ggplot(aes(x = displ, y = y[i],
>> color = c[i])) +     geom_point()
> 
> Your code relies on R's auto-printing, where each line of code executed
> at the top level (not in loops or functions) is run as if it was
> wrapped in print(...the rest of the line...).
> 
> Solution: make that print() explicit.
> 
> A better solution: explicitly pass the plot object returned by the
> ggplot functions to the ggsave() function instead of relying on the
> global state of the program.
> 
>> ggsave("c:/temp/f[i].jpg",width = 9, height = 6, dpi = 1200, units =
>> "in")
> 
> When you type "c:/temp/f[i].jpg", what do you get in return?
> 
> Use paste0() or sprintf() to compose strings out of parts.
> 
>>      [[alternative HTML version deleted]]
> 
> P.S. Please compose your messages in plain text, not HTML. See the
> R-help posting guide for more info.
> 
  
[[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] for loop question in R

2021-12-22 Thread Rui Barradas

Hello,

There's a stupid typo in my previous post. Inline

Às 22:30 de 22/12/21, Rui Barradas escreveu:

Hello,

y[i] and c[i] are character strings, they are not variables of data set 
mpg.

To get the variables, use, well, help("get").

Note that I have changed the temp dir to mine. So I created a variable 
to hold the value



tmpdir <- "c:/temp/"

for (i in seq(nrow(mac))){
   mpg %>%
     filter(hwy < 35) %>%
     ggplot(aes(x = displ, y = get(y[i]), color = get(c[i]))) +
     geom_point() +
     ylab(y[i]) +
     guides(color = guide_legend(title = c[i]))
   ggsave(
     paste0(tmpdir, f[i], ".jpg"),
     width = 9,
     height = 6,
     dpi = 1200,
     units = "in")
}



Like Ivan said, don't rely on auto print. In order to have to open the 


Should read

In order to *avoid* to open the


Rui Barradas


graphics files output by the loop I would have done something like the 
following.


First create a list to hold the plots. Inside the for loop save the 
plots in the list and explicitly print them. And use ggsave argument 
plot. Like this, after the loop you can see what you have by printing 
each list member.



p <- vector("list", length = nrow(mac))
for (i in seq(nrow(mac))){
   mpg %>%
     filter(hwy < 35) %>%
     ggplot(aes(x = displ, y = get(y[i]), color = get(c[i]))) +
     geom_point() +
     ylab(y[i]) +
     guides(color = guide_legend(title = c[i])) -> p[[i]]
   ggsave(
     paste0(tmpdir, f[i], ".jpg"),
     plot = p[[i]],
     width = 9,
     height = 6,
     dpi = 1200,
     units = "in")
}

# See the first plot
p[[1]]


Hope this helps,

Rui Barradas

Às 18:18 de 22/12/21, Kai Yang via R-help escreveu:

  Hello Eric, Jim and Ivan,
Many thanks all of your help. I'm a new one in R area. I may not fully 
understand the idea from you.  I modified my code below, I can get the 
plots out with correct file name, but plots  are not using correct 
fields' name. it use y[i], and c[i] as variables' name, does not use 
hwy, cyl or cty, class in ggplot statement. And there is not any error 
message. Could you please look into my modified code below and let me 
know how to modify y= y[i], color = c[i] part?

Thanks,
Kai

y <- c("hwy","cty")
c <- c("cyl","class")
f <- c("hwy_cyl","cty_class")
mac <- data.frame(y,c,f)
for (i in seq(nrow(mac))){
   mpg %>%
     filter(hwy <35) %>%
     ggplot(aes(x = displ, y = y[i], color = c[i])) +
     geom_point()
   ggsave(paste0("c:/temp/",f[i],".jpg"),width = 9, height = 6, dpi = 
1200, units = "in")

}

 On Wednesday, December 22, 2021, 09:42:45 AM PST, Ivan Krylov 
 wrote:

  On Wed, 22 Dec 2021 16:58:18 + (UTC)
Kai Yang via R-help  wrote:


mpg %>%    filter(hwy <35) %>%     ggplot(aes(x = displ, y = y[i],
color = c[i])) +     geom_point()


Your code relies on R's auto-printing, where each line of code executed
at the top level (not in loops or functions) is run as if it was
wrapped in print(...the rest of the line...).

Solution: make that print() explicit.

A better solution: explicitly pass the plot object returned by the
ggplot functions to the ggsave() function instead of relying on the
global state of the program.


ggsave("c:/temp/f[i].jpg",width = 9, height = 6, dpi = 1200, units =
"in")


When you type "c:/temp/f[i].jpg", what do you get in return?

Use paste0() or sprintf() to compose strings out of parts.


 [[alternative HTML version deleted]]


P.S. Please compose your messages in plain text, not HTML. See the
R-help posting guide for more info.



__
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] for loop question in R

2021-12-22 Thread Rui Barradas

Hello,

y[i] and c[i] are character strings, they are not variables of data set mpg.
To get the variables, use, well, help("get").

Note that I have changed the temp dir to mine. So I created a variable 
to hold the value



tmpdir <- "c:/temp/"

for (i in seq(nrow(mac))){
  mpg %>%
filter(hwy < 35) %>%
ggplot(aes(x = displ, y = get(y[i]), color = get(c[i]))) +
geom_point() +
ylab(y[i]) +
guides(color = guide_legend(title = c[i]))
  ggsave(
paste0(tmpdir, f[i], ".jpg"),
width = 9,
height = 6,
dpi = 1200,
units = "in")
}



Like Ivan said, don't rely on auto print. In order to have to open the 
graphics files output by the loop I would have done something like the 
following.


First create a list to hold the plots. Inside the for loop save the 
plots in the list and explicitly print them. And use ggsave argument 
plot. Like this, after the loop you can see what you have by printing 
each list member.



p <- vector("list", length = nrow(mac))
for (i in seq(nrow(mac))){
  mpg %>%
filter(hwy < 35) %>%
ggplot(aes(x = displ, y = get(y[i]), color = get(c[i]))) +
geom_point() +
ylab(y[i]) +
guides(color = guide_legend(title = c[i])) -> p[[i]]
  ggsave(
paste0(tmpdir, f[i], ".jpg"),
plot = p[[i]],
width = 9,
height = 6,
dpi = 1200,
units = "in")
}

# See the first plot
p[[1]]


Hope this helps,

Rui Barradas

Às 18:18 de 22/12/21, Kai Yang via R-help escreveu:

  Hello Eric, Jim and Ivan,
Many thanks all of your help. I'm a new one in R area. I may not fully 
understand the idea from you.  I modified my code below, I can get the plots 
out with correct file name, but plots  are not using correct fields' name. it 
use y[i], and c[i] as variables' name, does not use hwy, cyl or cty, class in 
ggplot statement. And there is not any error message. Could you please look 
into my modified code below and let me know how to modify y= y[i], color = c[i] 
part?
Thanks,
Kai

y <- c("hwy","cty")
c <- c("cyl","class")
f <- c("hwy_cyl","cty_class")
mac <- data.frame(y,c,f)
for (i in seq(nrow(mac))){
   mpg %>%
     filter(hwy <35) %>%
     ggplot(aes(x = displ, y = y[i], color = c[i])) +
     geom_point()
   ggsave(paste0("c:/temp/",f[i],".jpg"),width = 9, height = 6, dpi = 1200, units = 
"in")
}

 On Wednesday, December 22, 2021, 09:42:45 AM PST, Ivan Krylov 
 wrote:
  
  On Wed, 22 Dec 2021 16:58:18 + (UTC)

Kai Yang via R-help  wrote:


mpg %>%    filter(hwy <35) %>%     ggplot(aes(x = displ, y = y[i],
color = c[i])) +     geom_point()


Your code relies on R's auto-printing, where each line of code executed
at the top level (not in loops or functions) is run as if it was
wrapped in print(...the rest of the line...).

Solution: make that print() explicit.

A better solution: explicitly pass the plot object returned by the
ggplot functions to the ggsave() function instead of relying on the
global state of the program.


ggsave("c:/temp/f[i].jpg",width = 9, height = 6, dpi = 1200, units =
"in")


When you type "c:/temp/f[i].jpg", what do you get in return?

Use paste0() or sprintf() to compose strings out of parts.


     [[alternative HTML version deleted]]


P.S. Please compose your messages in plain text, not HTML. See the
R-help posting guide for more info.



__
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] for loop question in R

2021-12-22 Thread Kai Yang via R-help
 strange, I got error message when I run again:
Error: unexpected symbol in:
"    geom_point()
  ggsave"
> }
Error: unexpected '}' in "}"

On Wednesday, December 22, 2021, 10:18:56 AM PST, Kai Yang 
 wrote:  
 
  Hello Eric, Jim and Ivan,
Many thanks all of your help. I'm a new one in R area. I may not fully 
understand the idea from you.  I modified my code below, I can get the plots 
out with correct file name, but plots  are not using correct fields' name. it 
use y[i], and c[i] as variables' name, does not use hwy, cyl or cty, class in 
ggplot statement. And there is not any error message. Could you please look 
into my modified code below and let me know how to modify y= y[i], color = c[i] 
part?
Thanks,
Kai

y <- c("hwy","cty")
c <- c("cyl","class")
f <- c("hwy_cyl","cty_class")
mac <- data.frame(y,c,f)
for (i in seq(nrow(mac))){
  mpg %>%
    filter(hwy <35) %>% 
    ggplot(aes(x = displ, y = y[i], color = c[i])) + 
    geom_point()
  ggsave(paste0("c:/temp/",f[i],".jpg"),width = 9, height = 6, dpi = 1200, 
units = "in")
}

On Wednesday, December 22, 2021, 09:42:45 AM PST, Ivan Krylov 
 wrote:  
 
 On Wed, 22 Dec 2021 16:58:18 + (UTC)
Kai Yang via R-help  wrote:

> mpg %>%    filter(hwy <35) %>%     ggplot(aes(x = displ, y = y[i],
> color = c[i])) +     geom_point()

Your code relies on R's auto-printing, where each line of code executed
at the top level (not in loops or functions) is run as if it was
wrapped in print(...the rest of the line...).

Solution: make that print() explicit.

A better solution: explicitly pass the plot object returned by the
ggplot functions to the ggsave() function instead of relying on the
global state of the program.

> ggsave("c:/temp/f[i].jpg",width = 9, height = 6, dpi = 1200, units =
> "in")

When you type "c:/temp/f[i].jpg", what do you get in return?

Use paste0() or sprintf() to compose strings out of parts.

>     [[alternative HTML version deleted]]

P.S. Please compose your messages in plain text, not HTML. See the
R-help posting guide for more info.

-- 
Best regards,
Ivan

[[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] for loop question in R

2021-12-22 Thread Kai Yang via R-help
 Hello Eric, Jim and Ivan,
Many thanks all of your help. I'm a new one in R area. I may not fully 
understand the idea from you.  I modified my code below, I can get the plots 
out with correct file name, but plots  are not using correct fields' name. it 
use y[i], and c[i] as variables' name, does not use hwy, cyl or cty, class in 
ggplot statement. And there is not any error message. Could you please look 
into my modified code below and let me know how to modify y= y[i], color = c[i] 
part?
Thanks,
Kai

y <- c("hwy","cty")
c <- c("cyl","class")
f <- c("hwy_cyl","cty_class")
mac <- data.frame(y,c,f)
for (i in seq(nrow(mac))){
  mpg %>%
    filter(hwy <35) %>% 
    ggplot(aes(x = displ, y = y[i], color = c[i])) + 
    geom_point()
  ggsave(paste0("c:/temp/",f[i],".jpg"),width = 9, height = 6, dpi = 1200, 
units = "in")
}

On Wednesday, December 22, 2021, 09:42:45 AM PST, Ivan Krylov 
 wrote:  
 
 On Wed, 22 Dec 2021 16:58:18 + (UTC)
Kai Yang via R-help  wrote:

> mpg %>%    filter(hwy <35) %>%     ggplot(aes(x = displ, y = y[i],
> color = c[i])) +     geom_point()

Your code relies on R's auto-printing, where each line of code executed
at the top level (not in loops or functions) is run as if it was
wrapped in print(...the rest of the line...).

Solution: make that print() explicit.

A better solution: explicitly pass the plot object returned by the
ggplot functions to the ggsave() function instead of relying on the
global state of the program.

> ggsave("c:/temp/f[i].jpg",width = 9, height = 6, dpi = 1200, units =
> "in")

When you type "c:/temp/f[i].jpg", what do you get in return?

Use paste0() or sprintf() to compose strings out of parts.

>     [[alternative HTML version deleted]]

P.S. Please compose your messages in plain text, not HTML. See the
R-help posting guide for more info.

-- 
Best regards,
Ivan
  
[[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] for loop question in R

2021-12-22 Thread Ivan Krylov
On Wed, 22 Dec 2021 16:58:18 + (UTC)
Kai Yang via R-help  wrote:

> mpg %>%    filter(hwy <35) %>%     ggplot(aes(x = displ, y = y[i],
> color = c[i])) +     geom_point()

Your code relies on R's auto-printing, where each line of code executed
at the top level (not in loops or functions) is run as if it was
wrapped in print(...the rest of the line...).

Solution: make that print() explicit.

A better solution: explicitly pass the plot object returned by the
ggplot functions to the ggsave() function instead of relying on the
global state of the program.

> ggsave("c:/temp/f[i].jpg",width = 9, height = 6, dpi = 1200, units =
> "in")

When you type "c:/temp/f[i].jpg", what do you get in return?

Use paste0() or sprintf() to compose strings out of parts.

>   [[alternative HTML version deleted]]

P.S. Please compose your messages in plain text, not HTML. See the
R-help posting guide for more info.

-- 
Best regards,
Ivan

__
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] for loop question in R

2021-12-22 Thread jim holtman
You may have to add an explicit 'print' to ggplot

library(ggplot2)
library(tidyverse)
y <- c("hwy","cty")
c <- c("cyl","class")
f <- c("hwy_cyl","cty_class")
mac <- data.frame(y,c,f)
for (i in nrow(mac)){
  mpg %>%filter(hwy <35) %>%
 print(ggplot(aes(x = displ, y = y[i], color = c[i])) + geom_point())
  ggsave("c:/temp/f[i].jpg",width = 9, height = 6, dpi = 1200, units = "in")
}

Thanks

Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.


Thanks

Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.


On Wed, Dec 22, 2021 at 9:08 AM Kai Yang via R-help
 wrote:
>
> Hello R team,I want to use for loop to generate multiple plots with 3 
> parameter, (y is for y axis, c is for color and f is for file name in 
> output). I created a data frame to save the information and use the 
> information in for loop. I use y[i], c[i] and f[i] in the loop, but it seems 
> doesn't work. Can anyone correct my code to make it work?
> Thanks,Kai
>
> library(ggplot2)library(tidyverse)
> y <- c("hwy","cty")c <- c("cyl","class")f <- c("hwy_cyl","cty_class")
> mac <- data.frame(y,c,f)
> for (i in nrow(mac)){  mpg %>%filter(hwy <35) %>% ggplot(aes(x = 
> displ, y = y[i], color = c[i])) + geom_point()  
> ggsave("c:/temp/f[i].jpg",width = 9, height = 6, dpi = 1200, units = "in")}
>
> [[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] for loop question in R

2021-12-22 Thread Eric Berger
Try replacing
"c:/temp/f[i].jpg"
with
paste0("c:/temp/",f[i],".jpg")


On Wed, Dec 22, 2021 at 7:08 PM Kai Yang via R-help 
wrote:

> Hello R team,I want to use for loop to generate multiple plots with 3
> parameter, (y is for y axis, c is for color and f is for file name in
> output). I created a data frame to save the information and use the
> information in for loop. I use y[i], c[i] and f[i] in the loop, but it
> seems doesn't work. Can anyone correct my code to make it work?
> Thanks,Kai
>
> library(ggplot2)library(tidyverse)
> y <- c("hwy","cty")c <- c("cyl","class")f <- c("hwy_cyl","cty_class")
> mac <- data.frame(y,c,f)
> for (i in nrow(mac)){  mpg %>%filter(hwy <35) %>% ggplot(aes(x =
> displ, y = y[i], color = c[i])) + geom_point()
> ggsave("c:/temp/f[i].jpg",width = 9, height = 6, dpi = 1200, units = "in")}
>
> [[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.


Re: [R] for loop question in R

2021-12-22 Thread Andrew Simmons
nrow() is just the numbers of rows in your data frame, use seq_len(nrow())
or seq(nrow()) to loop through all row numbers

On Wed, Dec 22, 2021, 12:08 Kai Yang via R-help 
wrote:

> Hello R team,I want to use for loop to generate multiple plots with 3
> parameter, (y is for y axis, c is for color and f is for file name in
> output). I created a data frame to save the information and use the
> information in for loop. I use y[i], c[i] and f[i] in the loop, but it
> seems doesn't work. Can anyone correct my code to make it work?
> Thanks,Kai
>
> library(ggplot2)library(tidyverse)
> y <- c("hwy","cty")c <- c("cyl","class")f <- c("hwy_cyl","cty_class")
> mac <- data.frame(y,c,f)
> for (i in nrow(mac)){  mpg %>%filter(hwy <35) %>% ggplot(aes(x =
> displ, y = y[i], color = c[i])) + geom_point()
> ggsave("c:/temp/f[i].jpg",width = 9, height = 6, dpi = 1200, units = "in")}
>
> [[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] for loop question in R

2021-12-22 Thread Kai Yang via R-help
Hello R team,I want to use for loop to generate multiple plots with 3 
parameter, (y is for y axis, c is for color and f is for file name in output). 
I created a data frame to save the information and use the information in for 
loop. I use y[i], c[i] and f[i] in the loop, but it seems doesn't work. Can 
anyone correct my code to make it work?
Thanks,Kai

library(ggplot2)library(tidyverse)
y <- c("hwy","cty")c <- c("cyl","class")f <- c("hwy_cyl","cty_class")
mac <- data.frame(y,c,f)
for (i in nrow(mac)){  mpg %>%    filter(hwy <35) %>%     ggplot(aes(x = displ, 
y = y[i], color = c[i])) +     geom_point()  ggsave("c:/temp/f[i].jpg",width = 
9, height = 6, dpi = 1200, units = "in")}

[[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] Unending loop

2021-07-29 Thread Ivan Krylov
Hi Nick,

Thanks for providing an example that doesn't seem to depend on external
data!

On Thu, 29 Jul 2021 09:07:12 +0100
Nick Wray  wrote:

> I am looking at the extRemes package

It's probable that there aren't many extRemes users on R-help, but if
you contact the maintainer of extRemes (run maintainer('extRemes') to
get their name and address), you might get help that way.

> When I run it on my own laptop it works fine, but when I run it on my
> uni laptop (which is pretty new and I only was given a couple of
> months ago) when it gets to the thresh.range line it goes into an
> unending loop (or something) with the little red Stop button, and
> just sits there.

If you interrupt it there, backtrace() will point you in the direction
of seemingly endless loop. You can also set options(error = recover)
and get a debugger prompt at the point where you interrupted the code
or in any other frame. See ?browser and RShowDoc('R-lang') part 9
"Debugging" for more information.

> I have R 4.0.4 on my uni laptop and R 4.0.5 on my own one.  Could
> this be the reason?

I'm afraid it's easier for you to answer this question. It should be
possible to install R on computers even without administrator access.
Can you reproduce the issue with
https://cloud.r-project.org/bin/windows/base/old/4.0.4/ on your own
laptop or https://cloud.r-project.org/bin/windows/base/old/4.0.5/ on the
university-issued one?

>   [[alternative HTML version deleted]]

This mailing list strips away the HTML part of multipart/mixed
messages, so to make sure that your messages look exactly as you type
them, please compose them in plain text.

-- 
Best regards,
Ivan

__
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] Unending loop

2021-07-29 Thread Nick Wray
Hello I don't know whether strictly speaking this is an R-help province
question but anyway...
I am looking at the extRemes package and have some code given beneath.
When I run it on my own laptop it works fine, but when I run it on my uni
laptop (which is pretty new and I only was given a couple of months ago)
when it gets to the thresh.range line it goes into an unending loop (or
something) with the little red Stop button, and just sits there.  I have R
4.0.4 on my uni laptop and R 4.0.5 on my own one.  Could this be the reason?

Thanks, Nick Wray

install.packages("extRemes")
library(extRemes)
data(Fort)
names(Fort)

bmFort <- blockmaxxer(Fort, blocks = Fort$year, which="Prec")
names(bmFort)

plot(Fort$year, Fort$Prec, xlab = "Year",
 ylab = "Precipitation (inches)",
 cex = 1.25, cex.lab = 1.25,
 col = "darkblue", bg = "lightblue", pch = 21)

points(bmFort$year, bmFort$Prec, col="darkred", cex=1.5)

# Fit a GEV distribution to annual maximum Precipitation
# in Fort Collins, Colorado, U.S.A.
fitGEV <- fevd(Prec, data = bmFort)
fitGEV
plot(fitGEV)
plot(fitGEV, "trace")

# Select a threshold for daily data from above.
threshrange.plot(Fort$Prec, c(0.1, 2), type = "PP")

# Fit the PP model to the daily data from above.
fitPP <- fevd(Prec, data = Fort, threshold = 0.395,
  type = "PP", units = "inches")
fitPP
plot(fitPP)

atdf(Fort$Prec, 0.395)

extremalindex(Fort$Prec, 0.395, blocks=Fort$year)

dcFort <- decluster(Fort$Prec, 0.395, r = 9)
plot(dcFort)

[[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] "for" loop does not work with my plot_ly command

2021-03-30 Thread Bill Dunlap
Printing the return value of plot_ly and friends works for me in the
following examples:
# make base plot
p0 <- plotly::plot_ly(na.omit(palmerpenguins::penguins), x =
~bill_length_mm, y = ~body_mass_g)
# now add things to base plot
for(vrbl in list(~species, ~island, ~year)) {
   tmp <- plotly::add_markers(p0, symbol=vrbl, color=vrbl)
   print(tmp)
}
# or, the put the plots in a list
plots <- lapply(list(~species, ~island, ~year), function(vrbl)
plotly::add_markers(p0, symbol=vrbl, color=vrbl))
print(plots)



On Tue, Mar 30, 2021 at 2:26 AM Rachida El Ouaraini
 wrote:
>
> Hi Mika,
> and thank you very much for your answer.
> When I add the "for" loop to the code that produces before the graph I
> want, it does nothing :
> NO graph and NO error message.
> It seems to me that the command plot_ly and the for loop DO NOT coexist.
>
> Rachida
>
> On Mon, Mar 29, 2021 at 7:44 PM Mika Hamari 
> wrote:
>
> > Hi!
> >
> >
> >
> > I am also learning, but I want try to help. I often use for-loop in R. I
> > think that it could be due to dimensions of CPM, not the structure of the
> > loop.
> >
> >
> >
> > What kind of error message do you get? Is it: ”incorrect number of
> > dimensions”? What happens if you substitute in the end instead of CPM[i,1]
> > this:
> >
> >
> >
> > file.copy("C:/Users/pc/Downloads/Evolution Tmoy.png",
> > paste("C:/MONOGRAPHIE/Resultats/Evolution Tmoy_",CPM[i],".png",sep="")
> >
> >
> >
> > *Lähettäjä: *Rachida El Ouaraini 
> > *Lähetetty: *maanantai 29. maaliskuuta 2021 18.15
> > *Vastaanottaja: *r-help@r-project.org
> > *Aihe: *[R] "for" loop does not work with my plot_ly command
> >
> >
> >
> > Hi everyone,
> > I am new to R programming, and I am having difficulties modifying an R
> > script to introduce the "for" loop in the code.
> > While searching I found that this issue has already been raised, but I did
> > not know what to do to fix mine !
> >
> > *The code that works (without for command):*
> >
> > CPM <- read.table("FicConfig/CPM.txt" , header = TRUE, sep = "\t" , dec =
> > ",", skip = 0)
> > # The CPM.txt file containe 1 line
> > ..
> > ..
> > options(viewer = NULL)
> > plot_ly() %>%
> >  htmlwidgets::onRender(
> >"function(el, x) {
> >  var gd = document.getElementById(el.id);
> >  Plotly.downloadImage(gd, {format: 'png', width: 1000, height: 700,
> > filename: 'AnomalieRR_EcartTmoy'});
> >}"
> >  )%>%
> >  add_trace(x =TAnn[ ,3],  y = TAnn[ ,5], name = "Normale mensuelle de
> > Tmax(en °C)",type = 'scatter', mode = 'markers',  marker = list(size = T,
> > symbol = 'circle',  color = ~TAnn[ ,5], line = list(width= 2, color = cl)))
> > %>%
> > add_annotations(text = TAnn[ ,1], x= TAnn[ ,3], y = TAnn[ ,5], font =
> > list(color = "white", size = 14),  showarrow = FALSE)%>%
> >  layout(title = paste("Combinaison anomalie relative annuelle des
> > précipitations et écart annuel à la normale de la température moyenne  à
> > ",CPM[1,1],sep =""),
> >   xaxis = list(title = "Anomalie relative des précipitations
> > annuelles(en %)", tickangle = 20 ,titlefont = list(color= "blue", size= 14
> > , family = 'Arial'), tickfont = list(color = "blue", size = 14)),
> > yaxis = list(title = "Ecart à la normale de la température moyenne
> > annuelle(en°C)", titlefont = list(color= "red", size= 14 , family =
> > 'Arial'),
> > tickfont = list(color = "red", size = 14) , showline = TRUE, linecolor =
> > "red", linewidth = 2),
> >legend = list(x = 0.1, y = -0.3, font=list(size = 14,color=
> > "black")),margin = list(
> >   t = 70,
> >  r = 70,
> >   b = 70,
> >   l = 70
> > ))
> > *The code that does not work (with for command):*
> > CPM <- read.table("FicConfig/CPM.txt" , header = TRUE, sep = "\t" , dec =
> > ",", skip = 0)
> > # The CPM.txt file containe several lines
> >
> > *for (i in 1: (nrow(CPM)))   {*
> >
> > options(viewer = NULL)
> > plot_ly() %>%
> >  htmlwidgets::onRender(
> >"function(el, x) {
> >  var gd = document.getElementById(el.id);
> >  Plotly.downlo

Re: [R] "for" loop does not work with my plot_ly command

2021-03-30 Thread Mika Hamari
Hi!

That is familiar: loop goes on, but nothing visual happens. Normally when I 
don't get output of the loop, I put the output-line inside the function 
print(), and it works. But in this case it probably doesn't help. I am sure 
that someone here can help you, Rachida.

Mika



Lähetetty Samsung Galaxy -älypuhelimesta.


 Alkuperäinen viesti 
Lähettäjä: Rachida El Ouaraini 
Päivämäärä: 30.3.2021 12.25 (GMT+02:00)
Saaja: Mika Hamari 
Kopio: r-help@r-project.org
Aihe: Re: [R] "for" loop does not work with my plot_ly command

Hi Mika,
and thank you very much for your answer.
When I add the "for" loop to the code that produces before the graph I want, it 
does nothing :
NO graph and NO error message.
It seems to me that the command plot_ly and the for loop DO NOT coexist.

Rachida

On Mon, Mar 29, 2021 at 7:44 PM Mika Hamari 
mailto:mika.hamar...@outlook.com>> wrote:
Hi!

I am also learning, but I want try to help. I often use for-loop in R. I think 
that it could be due to dimensions of CPM, not the structure of the loop.

What kind of error message do you get? Is it: ”incorrect number of dimensions”? 
What happens if you substitute in the end instead of CPM[i,1] this:

file.copy("C:/Users/pc/Downloads/Evolution Tmoy.png",
paste("C:/MONOGRAPHIE/Resultats/Evolution Tmoy_",CPM[i],".png",sep="")

Lähettäjä: Rachida El Ouaraini<mailto:elouara...@gmail.com>
Lähetetty: maanantai 29. maaliskuuta 2021 18.15
Vastaanottaja: r-help@r-project.org<mailto:r-help@r-project.org>
Aihe: [R] "for" loop does not work with my plot_ly command

Hi everyone,
I am new to R programming, and I am having difficulties modifying an R
script to introduce the "for" loop in the code.
While searching I found that this issue has already been raised, but I did
not know what to do to fix mine !

*The code that works (without for command):*

CPM <- read.table("FicConfig/CPM.txt" , header = TRUE, sep = "\t" , dec =
",", skip = 0)
# The CPM.txt file containe 1 line
..
..
options(viewer = NULL)
plot_ly() %>%
 htmlwidgets::onRender(
   "function(el, x) {
 var gd = 
document.getElementById(el.id<https://emea01.safelinks.protection.outlook.com/?url=http%3A%2F%2Fel.id%2F=04%7C01%7C%7Cd44ce15fde0549644d4e08d8f35dca77%7C84df9e7fe9f640afb435%7C1%7C0%7C637526931442844620%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C1000=Nn3hw1AfZso8HiTjtOYAEkzplnB3QRSrFQ5qoyNwJVA%3D=0>);
 Plotly.downloadImage(gd, {format: 'png', width: 1000, height: 700,
filename: 'AnomalieRR_EcartTmoy'});
   }"
 )%>%
 add_trace(x =TAnn[ ,3],  y = TAnn[ ,5], name = "Normale mensuelle de
Tmax(en °C)",type = 'scatter', mode = 'markers',  marker = list(size = T,
symbol = 'circle',  color = ~TAnn[ ,5], line = list(width= 2, color = cl)))
%>%
add_annotations(text = TAnn[ ,1], x= TAnn[ ,3], y = TAnn[ ,5], font =
list(color = "white", size = 14),  showarrow = FALSE)%>%
 layout(title = paste("Combinaison anomalie relative annuelle des
précipitations et écart annuel à la normale de la température moyenne  à
",CPM[1,1],sep =""),
  xaxis = list(title = "Anomalie relative des précipitations
annuelles(en %)", tickangle = 20 ,titlefont = list(color= "blue", size= 14
, family = 'Arial'), tickfont = list(color = "blue", size = 14)),
yaxis = list(title = "Ecart à la normale de la température moyenne
annuelle(en°C)", titlefont = list(color= "red", size= 14 , family =
'Arial'),
tickfont = list(color = "red", size = 14) , showline = TRUE, linecolor =
"red", linewidth = 2),
   legend = list(x = 0.1, y = -0.3, font=list(size = 14,color=
"black")),margin = list(
  t = 70,
 r = 70,
  b = 70,
  l = 70
))
*The code that does not work (with for command):*
CPM <- read.table("FicConfig/CPM.txt" , header = TRUE, sep = "\t" , dec =
",", skip = 0)
# The CPM.txt file containe several lines

*for (i in 1: (nrow(CPM)))   {*

options(viewer = NULL)
plot_ly() %>%
 htmlwidgets::onRender(
   "function(el, x) {
 var gd = 
document.getElementById(el.id<https://emea01.safelinks.protection.outlook.com/?url=http%3A%2F%2Fel.id%2F=04%7C01%7C%7Cd44ce15fde0549644d4e08d8f35dca77%7C84df9e7fe9f640afb435%7C1%7C0%7C637526931442854613%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C1000=cjSxT%2BeaoRtlaDOKMHY910Pd0f8kJMVs35PErOpqfak%3D=0>);
 Plotly.downloadImage(gd, {format: 'png', width: 1000, height: 700,
filename: 'AnomalieRR_EcartTmoy'});
   }"
 )%>%
 add_trace(x =TAnn[ ,3],  y = TAnn[ ,5], name = &quo

Re: [R] "for" loop does not work with my plot_ly command

2021-03-30 Thread Rachida El Ouaraini
Hi Jim,
Many thanks for your answer !
I tried what you suggested but it doesn't work.
I've got NO error message, but nothing happens at the end : no graphs !
It seems to me that the command "plot_ly" and the "for" loop DO NOT
coexist, that's why I ask you how to overcome this problem?
Thank you again Dr Jim.

On Tue, Mar 30, 2021 at 4:37 AM Jim Lemon  wrote:

> Hi Rachida,
> My guess is that you create a vector of filenames:
>
> filenames<-list.files(path="FicConfig",pattern="*.txt")
>
> then use the filenames in the loop:
>
> for(filename in filenames) {
>  nextfile<- read.table(filename, header = TRUE, sep = "\t" , dec =
>  ",", skip = 0)
>  # do whatever you want with the resulting data frame here
>  # or perhaps save it into a list for processing later
> }
>
> Jim
>
> On Tue, Mar 30, 2021 at 2:15 AM Rachida El Ouaraini
>  wrote:
> >
> > Hi everyone,
> > I am new to R programming, and I am having difficulties modifying an R
> > script to introduce the "for" loop in the code.
> > While searching I found that this issue has already been raised, but I
> did
> > not know what to do to fix mine !
> >
> > *The code that works (without for command):*
> >
> > CPM <- read.table("FicConfig/CPM.txt" , header = TRUE, sep = "\t" , dec =
> > ",", skip = 0)
> > # The CPM.txt file containe 1 line
> > ..
> > ..
> > options(viewer = NULL)
> > plot_ly() %>%
> >  htmlwidgets::onRender(
> >"function(el, x) {
> >  var gd = document.getElementById(el.id);
> >  Plotly.downloadImage(gd, {format: 'png', width: 1000, height: 700,
> > filename: 'AnomalieRR_EcartTmoy'});
> >}"
> >  )%>%
> >  add_trace(x =TAnn[ ,3],  y = TAnn[ ,5], name = "Normale mensuelle de
> > Tmax(en °C)",type = 'scatter', mode = 'markers',  marker = list(size = T,
> > symbol = 'circle',  color = ~TAnn[ ,5], line = list(width= 2, color =
> cl)))
> > %>%
> > add_annotations(text = TAnn[ ,1], x= TAnn[ ,3], y = TAnn[ ,5], font =
> > list(color = "white", size = 14),  showarrow = FALSE)%>%
> >  layout(title = paste("Combinaison anomalie relative annuelle des
> > précipitations et écart annuel à la normale de la température moyenne  à
> > ",CPM[1,1],sep =""),
> >   xaxis = list(title = "Anomalie relative des précipitations
> > annuelles(en %)", tickangle = 20 ,titlefont = list(color= "blue", size=
> 14
> > , family = 'Arial'), tickfont = list(color = "blue", size = 14)),
> > yaxis = list(title = "Ecart à la normale de la température moyenne
> > annuelle(en°C)", titlefont = list(color= "red", size= 14 , family =
> > 'Arial'),
> > tickfont = list(color = "red", size = 14) , showline = TRUE, linecolor =
> > "red", linewidth = 2),
> >legend = list(x = 0.1, y = -0.3, font=list(size = 14,color=
> > "black")),margin = list(
> >   t = 70,
> >  r = 70,
> >   b = 70,
> >   l = 70
> > ))
> > *The code that does not work (with for command):*
> > CPM <- read.table("FicConfig/CPM.txt" , header = TRUE, sep = "\t" , dec =
> > ",", skip = 0)
> > # The CPM.txt file containe several lines
> >
> > *for (i in 1: (nrow(CPM)))   {*
> >
> > options(viewer = NULL)
> > plot_ly() %>%
> >  htmlwidgets::onRender(
> >"function(el, x) {
> >  var gd = document.getElementById(el.id);
> >  Plotly.downloadImage(gd, {format: 'png', width: 1000, height: 700,
> > filename: 'AnomalieRR_EcartTmoy'});
> >}"
> >  )%>%
> >  add_trace(x =TAnn[ ,3],  y = TAnn[ ,5], name = "Normale mensuelle de
> > Tmax(en °C)",type = 'scatter', mode = 'markers',  marker = list(size = T,
> > symbol = 'circle',  color = ~TAnn[ ,5], line = list(width= 2, color =
> cl)))
> > %>%
> > add_annotations(text = TAnn[ ,1], x= TAnn[ ,3], y = TAnn[ ,5], font =
> > list(color = "white", size = 14),  showarrow = FALSE)%>%
> >   layout(title = paste("Combinaison anomalie relative annuelle des
> > précipitations et écart annuel à la normale de la température moyenne  à
> > ",CPM[i,1],sep =""),
> >   xaxis = list(title = "Anomalie relative des précipitations
> > annuelles(en %)", tickangle = 20 ,titlefont = list(color= "blue", size=
> 14
> > , family = 'Arial'), tickfont = list(color = "blue", size = 14)),
> > yaxis = list(title = "Ecart à la normale de la température moyenne
> > annuelle(en°C)", titlefont = list(color= "red", size= 14 , family =
> > 'Arial'),
> > tickfont = list(color = "red", size = 14) , showline = TRUE, linecolor =
> > "red", linewidth = 2),
> >   legend = list(x = 0.1, y = -0.3, font=list(size = 14,color=
> > "black")),margin = list(
> >   t = 70,
> >  r = 70,
> >   b = 70,
> >   l = 70
> > ))
> >
> > *file.copy("C:/Users/pc/Downloads/Evolution Tmoy.png",
> > paste("C:/MONOGRAPHIE/Resultats/Evolution Tmoy_",CPM[i,1],".png",sep="")*
> > *}*
> >
> >
> > Thank you very much in advance for any help.
> >
> > [[alternative HTML version deleted]]
> >
> > __
> > 

Re: [R] "for" loop does not work with my plot_ly command

2021-03-30 Thread Rachida El Ouaraini
Hi Mika,
and thank you very much for your answer.
When I add the "for" loop to the code that produces before the graph I
want, it does nothing :
NO graph and NO error message.
It seems to me that the command plot_ly and the for loop DO NOT coexist.

Rachida

On Mon, Mar 29, 2021 at 7:44 PM Mika Hamari 
wrote:

> Hi!
>
>
>
> I am also learning, but I want try to help. I often use for-loop in R. I
> think that it could be due to dimensions of CPM, not the structure of the
> loop.
>
>
>
> What kind of error message do you get? Is it: ”incorrect number of
> dimensions”? What happens if you substitute in the end instead of CPM[i,1]
> this:
>
>
>
> file.copy("C:/Users/pc/Downloads/Evolution Tmoy.png",
> paste("C:/MONOGRAPHIE/Resultats/Evolution Tmoy_",CPM[i],".png",sep="")
>
>
>
> *Lähettäjä: *Rachida El Ouaraini 
> *Lähetetty: *maanantai 29. maaliskuuta 2021 18.15
> *Vastaanottaja: *r-help@r-project.org
> *Aihe: *[R] "for" loop does not work with my plot_ly command
>
>
>
> Hi everyone,
> I am new to R programming, and I am having difficulties modifying an R
> script to introduce the "for" loop in the code.
> While searching I found that this issue has already been raised, but I did
> not know what to do to fix mine !
>
> *The code that works (without for command):*
>
> CPM <- read.table("FicConfig/CPM.txt" , header = TRUE, sep = "\t" , dec =
> ",", skip = 0)
> # The CPM.txt file containe 1 line
> ..
> ..
> options(viewer = NULL)
> plot_ly() %>%
>  htmlwidgets::onRender(
>"function(el, x) {
>  var gd = document.getElementById(el.id);
>  Plotly.downloadImage(gd, {format: 'png', width: 1000, height: 700,
> filename: 'AnomalieRR_EcartTmoy'});
>}"
>  )%>%
>  add_trace(x =TAnn[ ,3],  y = TAnn[ ,5], name = "Normale mensuelle de
> Tmax(en °C)",type = 'scatter', mode = 'markers',  marker = list(size = T,
> symbol = 'circle',  color = ~TAnn[ ,5], line = list(width= 2, color = cl)))
> %>%
> add_annotations(text = TAnn[ ,1], x= TAnn[ ,3], y = TAnn[ ,5], font =
> list(color = "white", size = 14),  showarrow = FALSE)%>%
>  layout(title = paste("Combinaison anomalie relative annuelle des
> précipitations et écart annuel à la normale de la température moyenne  à
> ",CPM[1,1],sep =""),
>   xaxis = list(title = "Anomalie relative des précipitations
> annuelles(en %)", tickangle = 20 ,titlefont = list(color= "blue", size= 14
> , family = 'Arial'), tickfont = list(color = "blue", size = 14)),
> yaxis = list(title = "Ecart à la normale de la température moyenne
> annuelle(en°C)", titlefont = list(color= "red", size= 14 , family =
> 'Arial'),
> tickfont = list(color = "red", size = 14) , showline = TRUE, linecolor =
> "red", linewidth = 2),
>legend = list(x = 0.1, y = -0.3, font=list(size = 14,color=
> "black")),margin = list(
>   t = 70,
>  r = 70,
>   b = 70,
>   l = 70
> ))
> *The code that does not work (with for command):*
> CPM <- read.table("FicConfig/CPM.txt" , header = TRUE, sep = "\t" , dec =
> ",", skip = 0)
> # The CPM.txt file containe several lines
>
> *for (i in 1: (nrow(CPM)))   {*
>
> options(viewer = NULL)
> plot_ly() %>%
>  htmlwidgets::onRender(
>"function(el, x) {
>  var gd = document.getElementById(el.id);
>  Plotly.downloadImage(gd, {format: 'png', width: 1000, height: 700,
> filename: 'AnomalieRR_EcartTmoy'});
>}"
>  )%>%
>  add_trace(x =TAnn[ ,3],  y = TAnn[ ,5], name = "Normale mensuelle de
> Tmax(en °C)",type = 'scatter', mode = 'markers',  marker = list(size = T,
> symbol = 'circle',  color = ~TAnn[ ,5], line = list(width= 2, color = cl)))
> %>%
> add_annotations(text = TAnn[ ,1], x= TAnn[ ,3], y = TAnn[ ,5], font =
> list(color = "white", size = 14),  showarrow = FALSE)%>%
>   layout(title = paste("Combinaison anomalie relative annuelle des
> précipitations et écart annuel à la normale de la température moyenne  à
> ",CPM[i,1],sep =""),
>   xaxis = list(title = "Anomalie relative des précipitations
> annuelles(en %)", tickangle = 20 ,titlefont = list(color= "blue", size= 14
> , family = 'Arial'), tickfont = list(color = "blue", size = 14)),
> yaxis = list(title = "Ecart à la normale de la température moyenne
> annuelle(en°C)

Re: [R] "for" loop does not work with my plot_ly command

2021-03-29 Thread Jim Lemon
Hi Rachida,
My guess is that you create a vector of filenames:

filenames<-list.files(path="FicConfig",pattern="*.txt")

then use the filenames in the loop:

for(filename in filenames) {
 nextfile<- read.table(filename, header = TRUE, sep = "\t" , dec =
 ",", skip = 0)
 # do whatever you want with the resulting data frame here
 # or perhaps save it into a list for processing later
}

Jim

On Tue, Mar 30, 2021 at 2:15 AM Rachida El Ouaraini
 wrote:
>
> Hi everyone,
> I am new to R programming, and I am having difficulties modifying an R
> script to introduce the "for" loop in the code.
> While searching I found that this issue has already been raised, but I did
> not know what to do to fix mine !
>
> *The code that works (without for command):*
>
> CPM <- read.table("FicConfig/CPM.txt" , header = TRUE, sep = "\t" , dec =
> ",", skip = 0)
> # The CPM.txt file containe 1 line
> ..
> ..
> options(viewer = NULL)
> plot_ly() %>%
>  htmlwidgets::onRender(
>"function(el, x) {
>  var gd = document.getElementById(el.id);
>  Plotly.downloadImage(gd, {format: 'png', width: 1000, height: 700,
> filename: 'AnomalieRR_EcartTmoy'});
>}"
>  )%>%
>  add_trace(x =TAnn[ ,3],  y = TAnn[ ,5], name = "Normale mensuelle de
> Tmax(en °C)",type = 'scatter', mode = 'markers',  marker = list(size = T,
> symbol = 'circle',  color = ~TAnn[ ,5], line = list(width= 2, color = cl)))
> %>%
> add_annotations(text = TAnn[ ,1], x= TAnn[ ,3], y = TAnn[ ,5], font =
> list(color = "white", size = 14),  showarrow = FALSE)%>%
>  layout(title = paste("Combinaison anomalie relative annuelle des
> précipitations et écart annuel à la normale de la température moyenne  à
> ",CPM[1,1],sep =""),
>   xaxis = list(title = "Anomalie relative des précipitations
> annuelles(en %)", tickangle = 20 ,titlefont = list(color= "blue", size= 14
> , family = 'Arial'), tickfont = list(color = "blue", size = 14)),
> yaxis = list(title = "Ecart à la normale de la température moyenne
> annuelle(en°C)", titlefont = list(color= "red", size= 14 , family =
> 'Arial'),
> tickfont = list(color = "red", size = 14) , showline = TRUE, linecolor =
> "red", linewidth = 2),
>legend = list(x = 0.1, y = -0.3, font=list(size = 14,color=
> "black")),margin = list(
>   t = 70,
>  r = 70,
>   b = 70,
>   l = 70
> ))
> *The code that does not work (with for command):*
> CPM <- read.table("FicConfig/CPM.txt" , header = TRUE, sep = "\t" , dec =
> ",", skip = 0)
> # The CPM.txt file containe several lines
>
> *for (i in 1: (nrow(CPM)))   {*
>
> options(viewer = NULL)
> plot_ly() %>%
>  htmlwidgets::onRender(
>"function(el, x) {
>  var gd = document.getElementById(el.id);
>  Plotly.downloadImage(gd, {format: 'png', width: 1000, height: 700,
> filename: 'AnomalieRR_EcartTmoy'});
>}"
>  )%>%
>  add_trace(x =TAnn[ ,3],  y = TAnn[ ,5], name = "Normale mensuelle de
> Tmax(en °C)",type = 'scatter', mode = 'markers',  marker = list(size = T,
> symbol = 'circle',  color = ~TAnn[ ,5], line = list(width= 2, color = cl)))
> %>%
> add_annotations(text = TAnn[ ,1], x= TAnn[ ,3], y = TAnn[ ,5], font =
> list(color = "white", size = 14),  showarrow = FALSE)%>%
>   layout(title = paste("Combinaison anomalie relative annuelle des
> précipitations et écart annuel à la normale de la température moyenne  à
> ",CPM[i,1],sep =""),
>   xaxis = list(title = "Anomalie relative des précipitations
> annuelles(en %)", tickangle = 20 ,titlefont = list(color= "blue", size= 14
> , family = 'Arial'), tickfont = list(color = "blue", size = 14)),
> yaxis = list(title = "Ecart à la normale de la température moyenne
> annuelle(en°C)", titlefont = list(color= "red", size= 14 , family =
> 'Arial'),
> tickfont = list(color = "red", size = 14) , showline = TRUE, linecolor =
> "red", linewidth = 2),
>   legend = list(x = 0.1, y = -0.3, font=list(size = 14,color=
> "black")),margin = list(
>   t = 70,
>  r = 70,
>   b = 70,
>   l = 70
> ))
>
> *file.copy("C:/Users/pc/Downloads/Evolution Tmoy.png",
> paste("C:/MONOGRAPHIE/Resultats/Evolution Tmoy_",CPM[i,1],".png",sep="")*
> *}*
>
>
> Thank you very much in advance for any help.
>
> [[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] "for" loop does not work with my plot_ly command

2021-03-29 Thread Mika Hamari
Hi!

I am also learning, but I want try to help. I often use for-loop in R. I think 
that it could be due to dimensions of CPM, not the structure of the loop.

What kind of error message do you get? Is it: �incorrect number of dimensions�? 
What happens if you substitute in the end instead of CPM[i,1] this:

file.copy("C:/Users/pc/Downloads/Evolution Tmoy.png",
paste("C:/MONOGRAPHIE/Resultats/Evolution Tmoy_",CPM[i],".png",sep="")

L�hett�j�: Rachida El Ouaraini<mailto:elouara...@gmail.com>
L�hetetty: maanantai 29. maaliskuuta 2021 18.15
Vastaanottaja: r-help@r-project.org<mailto:r-help@r-project.org>
Aihe: [R] "for" loop does not work with my plot_ly command

Hi everyone,
I am new to R programming, and I am having difficulties modifying an R
script to introduce the "for" loop in the code.
While searching I found that this issue has already been raised, but I did
not know what to do to fix mine !

*The code that works (without for command):*

CPM <- read.table("FicConfig/CPM.txt" , header = TRUE, sep = "\t" , dec =
",", skip = 0)
# The CPM.txt file containe 1 line
..
..
options(viewer = NULL)
plot_ly() %>%
 htmlwidgets::onRender(
   "function(el, x) {
 var gd = document.getElementById(el.id);
 Plotly.downloadImage(gd, {format: 'png', width: 1000, height: 700,
filename: 'AnomalieRR_EcartTmoy'});
   }"
 )%>%
 add_trace(x =TAnn[ ,3],  y = TAnn[ ,5], name = "Normale mensuelle de
Tmax(en �C)",type = 'scatter', mode = 'markers',  marker = list(size = T,
symbol = 'circle',  color = ~TAnn[ ,5], line = list(width= 2, color = cl)))
%>%
add_annotations(text = TAnn[ ,1], x= TAnn[ ,3], y = TAnn[ ,5], font =
list(color = "white", size = 14),  showarrow = FALSE)%>%
 layout(title = paste("Combinaison anomalie relative annuelle des
pr�cipitations et �cart annuel � la normale de la temp�rature moyenne  �
",CPM[1,1],sep =""),
  xaxis = list(title = "Anomalie relative des pr�cipitations
annuelles(en %)", tickangle = 20 ,titlefont = list(color= "blue", size= 14
, family = 'Arial'), tickfont = list(color = "blue", size = 14)),
yaxis = list(title = "Ecart � la normale de la temp�rature moyenne
annuelle(en�C)", titlefont = list(color= "red", size= 14 , family =
'Arial'),
tickfont = list(color = "red", size = 14) , showline = TRUE, linecolor =
"red", linewidth = 2),
   legend = list(x = 0.1, y = -0.3, font=list(size = 14,color=
"black")),margin = list(
  t = 70,
 r = 70,
  b = 70,
  l = 70
))
*The code that does not work (with for command):*
CPM <- read.table("FicConfig/CPM.txt" , header = TRUE, sep = "\t" , dec =
",", skip = 0)
# The CPM.txt file containe several lines

*for (i in 1: (nrow(CPM)))   {*

options(viewer = NULL)
plot_ly() %>%
 htmlwidgets::onRender(
   "function(el, x) {
 var gd = document.getElementById(el.id);
 Plotly.downloadImage(gd, {format: 'png', width: 1000, height: 700,
filename: 'AnomalieRR_EcartTmoy'});
   }"
 )%>%
 add_trace(x =TAnn[ ,3],  y = TAnn[ ,5], name = "Normale mensuelle de
Tmax(en �C)",type = 'scatter', mode = 'markers',  marker = list(size = T,
symbol = 'circle',  color = ~TAnn[ ,5], line = list(width= 2, color = cl)))
%>%
add_annotations(text = TAnn[ ,1], x= TAnn[ ,3], y = TAnn[ ,5], font =
list(color = "white", size = 14),  showarrow = FALSE)%>%
  layout(title = paste("Combinaison anomalie relative annuelle des
pr�cipitations et �cart annuel � la normale de la temp�rature moyenne  �
",CPM[i,1],sep =""),
  xaxis = list(title = "Anomalie relative des pr�cipitations
annuelles(en %)", tickangle = 20 ,titlefont = list(color= "blue", size= 14
, family = 'Arial'), tickfont = list(color = "blue", size = 14)),
yaxis = list(title = "Ecart � la normale de la temp�rature moyenne
annuelle(en�C)", titlefont = list(color= "red", size= 14 , family =
'Arial'),
tickfont = list(color = "red", size = 14) , showline = TRUE, linecolor =
"red", linewidth = 2),
  legend = list(x = 0.1, y = -0.3, font=list(size = 14,color=
"black")),margin = list(
  t = 70,
 r = 70,
  b = 70,
  l = 70
))

*file.copy("C:/Users/pc/Downloads/Evolution Tmoy.png",
paste("C:/MONOGRAPHIE/Resultats/Evolution Tmoy_",CPM[i,1],".png",sep="")*
*}*


Thank you very much in advance for any help.

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://emea01.safelinks.protection.outlo

[R] "for" loop does not work with my plot_ly command

2021-03-29 Thread Rachida El Ouaraini
Hi everyone,
I am new to R programming, and I am having difficulties modifying an R
script to introduce the "for" loop in the code.
While searching I found that this issue has already been raised, but I did
not know what to do to fix mine !

*The code that works (without for command):*

CPM <- read.table("FicConfig/CPM.txt" , header = TRUE, sep = "\t" , dec =
",", skip = 0)
# The CPM.txt file containe 1 line
..
..
options(viewer = NULL)
plot_ly() %>%
 htmlwidgets::onRender(
   "function(el, x) {
 var gd = document.getElementById(el.id);
 Plotly.downloadImage(gd, {format: 'png', width: 1000, height: 700,
filename: 'AnomalieRR_EcartTmoy'});
   }"
 )%>%
 add_trace(x =TAnn[ ,3],  y = TAnn[ ,5], name = "Normale mensuelle de
Tmax(en °C)",type = 'scatter', mode = 'markers',  marker = list(size = T,
symbol = 'circle',  color = ~TAnn[ ,5], line = list(width= 2, color = cl)))
%>%
add_annotations(text = TAnn[ ,1], x= TAnn[ ,3], y = TAnn[ ,5], font =
list(color = "white", size = 14),  showarrow = FALSE)%>%
 layout(title = paste("Combinaison anomalie relative annuelle des
précipitations et écart annuel à la normale de la température moyenne  à
",CPM[1,1],sep =""),
  xaxis = list(title = "Anomalie relative des précipitations
annuelles(en %)", tickangle = 20 ,titlefont = list(color= "blue", size= 14
, family = 'Arial'), tickfont = list(color = "blue", size = 14)),
yaxis = list(title = "Ecart à la normale de la température moyenne
annuelle(en°C)", titlefont = list(color= "red", size= 14 , family =
'Arial'),
tickfont = list(color = "red", size = 14) , showline = TRUE, linecolor =
"red", linewidth = 2),
   legend = list(x = 0.1, y = -0.3, font=list(size = 14,color=
"black")),margin = list(
  t = 70,
 r = 70,
  b = 70,
  l = 70
))
*The code that does not work (with for command):*
CPM <- read.table("FicConfig/CPM.txt" , header = TRUE, sep = "\t" , dec =
",", skip = 0)
# The CPM.txt file containe several lines

*for (i in 1: (nrow(CPM)))   {*

options(viewer = NULL)
plot_ly() %>%
 htmlwidgets::onRender(
   "function(el, x) {
 var gd = document.getElementById(el.id);
 Plotly.downloadImage(gd, {format: 'png', width: 1000, height: 700,
filename: 'AnomalieRR_EcartTmoy'});
   }"
 )%>%
 add_trace(x =TAnn[ ,3],  y = TAnn[ ,5], name = "Normale mensuelle de
Tmax(en °C)",type = 'scatter', mode = 'markers',  marker = list(size = T,
symbol = 'circle',  color = ~TAnn[ ,5], line = list(width= 2, color = cl)))
%>%
add_annotations(text = TAnn[ ,1], x= TAnn[ ,3], y = TAnn[ ,5], font =
list(color = "white", size = 14),  showarrow = FALSE)%>%
  layout(title = paste("Combinaison anomalie relative annuelle des
précipitations et écart annuel à la normale de la température moyenne  à
",CPM[i,1],sep =""),
  xaxis = list(title = "Anomalie relative des précipitations
annuelles(en %)", tickangle = 20 ,titlefont = list(color= "blue", size= 14
, family = 'Arial'), tickfont = list(color = "blue", size = 14)),
yaxis = list(title = "Ecart à la normale de la température moyenne
annuelle(en°C)", titlefont = list(color= "red", size= 14 , family =
'Arial'),
tickfont = list(color = "red", size = 14) , showline = TRUE, linecolor =
"red", linewidth = 2),
  legend = list(x = 0.1, y = -0.3, font=list(size = 14,color=
"black")),margin = list(
  t = 70,
 r = 70,
  b = 70,
  l = 70
))

*file.copy("C:/Users/pc/Downloads/Evolution Tmoy.png",
paste("C:/MONOGRAPHIE/Resultats/Evolution Tmoy_",CPM[i,1],".png",sep="")*
*}*


Thank you very much in advance for any help.

[[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] for loop implementation in below problem

2021-03-22 Thread Jim Lemon
No, I am confounded, It does return the value of the expressions
within the respective braces, just like ifelse. Learn something every
day.

Jim

On Mon, Mar 22, 2021 at 9:35 PM Jim Lemon  wrote:
>
> If he's setting PRE to the return value of "if", that is the logical
> value of the expression in the if statement as far as I know. I think
> that the expression within the else clause would be evaluated but not
> assigned to anything and since it is within the loop, would just be
> lost.
>
> PRE<-ifelse(missing(GAY),(GA/GA)*100,(GA/GAY)*100)
>
> would return either value depending upon whether GAY was missing.
> That's what I get from the help pages.
>
> Jim
>
> On Mon, Mar 22, 2021 at 8:34 PM Duncan Murdoch  
> wrote:
> >
> > On 22/03/2021 1:59 a.m., Jim Lemon wrote:
> > > Hi Goyani,
> > > You are setting "PRE" to the return value of "if" which is one of TRUE
> > > (1), FALSE(0) or NULL.
> >
> > That's not true at all.  The statement was
> >
> >  PRE<- if(missing(GAY)){
> >(GA/GA) * 100
> >  } else {
> >(GA/GAY) * 100
> >  }
> >
> > so the result is (GA/GA) * 100 or (GA/GAY)*100.
> >
> > > Because GAY is always missing in your example,
> >
> > If that's true and GA isn't missing, the result will always be 100.
> >
> > Duncan Murdoch
> >
> > > "PRE" is always set to 1. Then you always want to pass 1 in the sample
> > > list, and that will not assign anything to PRE. By correcting the "if"
> > > clause and defining matrices that are unlikely to be singular, I can
> > > run a "for" loop as follows:
> > >
> > > selection.index<- function(ID, phen_mat, gen_mat, weight_mat, GAY){
> > >   p<-as.matrix(phen_mat)
> > >   g<-as.matrix(gen_mat)
> > >   w<-as.matrix(weight_mat)
> > >   bmat<- solve(phen_mat) %*% gen_mat %*% weight_mat
> > >   GA<- 2.063 * t(bmat) %*% g %*% w / (t(bmat) %*% p %*% bmat)^0.5
> > >   if(missing(GAY)) PRE<-(GA/GA) * 100
> > >   else PRE<-(GA/GAY) * 100
> > >   result<-list(ID=ID,b=matrix(round(bmat,4),nrow=1),
> > >GA=round(GA,4),PRE=round(PRE,4))
> > >   return(data.frame(result))
> > > }
> > >
> > > pmat<-matrix(sample(1:16,16),4)
> > > gmat<-matrix(sample(17:32),16,4)
> > > wmat<-matrix(sample(1:4,4),4)
> > >
> > > mi<-combn(1:4,2)
> > > sc<-list()
> > > for(i in 1:ncol(matindx)) {
> > >   as.numeric(ID<-paste0(mi[,i]))
> > >   sc[[i]]<-selection.index(ID,pmat[mi[,i],mi[,i]],gmat[mi[,i],mi[,i]],
> > >wmat[mi[,i]],1)
> > > }
> > >
> > > This produces output for me. Good luck with whatever you are doing with 
> > > this.
> > >
> > > Jim
> > >
> > >
> > >
> > >
> > >
> > > On Mon, Mar 22, 2021 at 2:51 PM Goyani Zankrut  
> > > wrote:
> > >>
> > >> Greetings of the day,
> > >> Thank you for your response, Sir.
> > >> The full problem statement is given below:
> > >>
> > >> In our case, I'm taking 4 traits.
> > >> library(arrangements)
> > >> a<- combinations(4,2) # gives 6 pairwise combinations
> > >> class(a) # it's a "matrix" "array"
> > >>
> > >> now hypothetical data of three matrix for further calculation:
> > >> pmat<- matrix(1:16, nrow = 4)
> > >> gmat<- matrix(17:32, nrow = 4)
> > >> wmat<- matrix(1:4, nrow = 4)
> > >>
> > >> My custom function for further calculations:
> > >> selection.index<- function(ID, phen_mat, gen_mat, weight_mat, GAY){
> > >>ID = toString(ID)
> > >>p<- as.matrix(phen_mat)
> > >>g<- as.matrix(gen_mat)
> > >>w<- as.matrix(weight_mat)
> > >>bmat<- solve(phen_mat) %*% gen_mat %*% weight_mat
> > >>GA<- 2.063 * t(bmat) %*% g %*% w / (t(bmat) %*% p %*% bmat)^0.5
> > >>PRE<- if(missing(GAY)){
> > >>  (GA/GA) * 100
> > >>} else {
> > >>  (GA/GAY) * 100
> > >>}
> > >>result<- list("ID" = ID, "b" = matrix(round(bmat,4), nrow = 1), "GA" 
> > >> = round(GA,4), "PRE" = round(PRE,4))
> > >>return(data.frame(result))
> > >> }
> > >>
> > >> Now I want to store this data into a list for further calculation:
> > >> sc<- list()
> > >> sc[[1]]<- selection.index(ID = 12, phen_mat = pmat[c(1,2),c(1,2)], 
> > >> gen_mat = gmat[c(1,2),c(1,2)], weight_mat = wmat[c(1,2),1])
> > >> sc[[2]]<- selection.index(ID = 13, phen_mat = pmat[c(1,3),c(1,3)], 
> > >> gen_mat = gmat[c(1,3),c(1,3)], weight_mat = wmat[c(1,3),1])
> > >> sc[[3]]<- selection.index(ID = 14, phen_mat = pmat[c(1,4),c(1,4)], 
> > >> gen_mat = gmat[c(1,4),c(1,4)], weight_mat = wmat[c(1,4),1])
> > >> sc[[4]]<- selection.index(ID = 23, phen_mat = pmat[c(2,3),c(2,3)], 
> > >> gen_mat = gmat[c(2,3),c(2,3)], weight_mat = wmat[c(2,3),1])
> > >> sc[[5]]<- selection.index(ID = 24, phen_mat = pmat[c(2,4),c(2,4)], 
> > >> gen_mat = gmat[c(2,4),c(2,4)], weight_mat = wmat[c(2,4),1])
> > >> sc[[6]]<- selection.index(ID = 34, phen_mat = pmat[c(3,4),c(3,4)], 
> > >> gen_mat = gmat[c(3,4),c(3,4)], weight_mat = wmat[c(3,4),1])
> > >> above list code is monotonous and time consuming for large data 
> > >> combination cycles like (7,2) = 21 combinations, (10,2) = 45 
> > >> combinations. So I want to use the matrix a's each row as a vector in 
> > >> the 

Re: [R] for loop implementation in below problem

2021-03-22 Thread Jim Lemon
If he's setting PRE to the return value of "if", that is the logical
value of the expression in the if statement as far as I know. I think
that the expression within the else clause would be evaluated but not
assigned to anything and since it is within the loop, would just be
lost.

PRE<-ifelse(missing(GAY),(GA/GA)*100,(GA/GAY)*100)

would return either value depending upon whether GAY was missing.
That's what I get from the help pages.

Jim

On Mon, Mar 22, 2021 at 8:34 PM Duncan Murdoch  wrote:
>
> On 22/03/2021 1:59 a.m., Jim Lemon wrote:
> > Hi Goyani,
> > You are setting "PRE" to the return value of "if" which is one of TRUE
> > (1), FALSE(0) or NULL.
>
> That's not true at all.  The statement was
>
>  PRE<- if(missing(GAY)){
>(GA/GA) * 100
>  } else {
>(GA/GAY) * 100
>  }
>
> so the result is (GA/GA) * 100 or (GA/GAY)*100.
>
> > Because GAY is always missing in your example,
>
> If that's true and GA isn't missing, the result will always be 100.
>
> Duncan Murdoch
>
> > "PRE" is always set to 1. Then you always want to pass 1 in the sample
> > list, and that will not assign anything to PRE. By correcting the "if"
> > clause and defining matrices that are unlikely to be singular, I can
> > run a "for" loop as follows:
> >
> > selection.index<- function(ID, phen_mat, gen_mat, weight_mat, GAY){
> >   p<-as.matrix(phen_mat)
> >   g<-as.matrix(gen_mat)
> >   w<-as.matrix(weight_mat)
> >   bmat<- solve(phen_mat) %*% gen_mat %*% weight_mat
> >   GA<- 2.063 * t(bmat) %*% g %*% w / (t(bmat) %*% p %*% bmat)^0.5
> >   if(missing(GAY)) PRE<-(GA/GA) * 100
> >   else PRE<-(GA/GAY) * 100
> >   result<-list(ID=ID,b=matrix(round(bmat,4),nrow=1),
> >GA=round(GA,4),PRE=round(PRE,4))
> >   return(data.frame(result))
> > }
> >
> > pmat<-matrix(sample(1:16,16),4)
> > gmat<-matrix(sample(17:32),16,4)
> > wmat<-matrix(sample(1:4,4),4)
> >
> > mi<-combn(1:4,2)
> > sc<-list()
> > for(i in 1:ncol(matindx)) {
> >   as.numeric(ID<-paste0(mi[,i]))
> >   sc[[i]]<-selection.index(ID,pmat[mi[,i],mi[,i]],gmat[mi[,i],mi[,i]],
> >wmat[mi[,i]],1)
> > }
> >
> > This produces output for me. Good luck with whatever you are doing with 
> > this.
> >
> > Jim
> >
> >
> >
> >
> >
> > On Mon, Mar 22, 2021 at 2:51 PM Goyani Zankrut  wrote:
> >>
> >> Greetings of the day,
> >> Thank you for your response, Sir.
> >> The full problem statement is given below:
> >>
> >> In our case, I'm taking 4 traits.
> >> library(arrangements)
> >> a<- combinations(4,2) # gives 6 pairwise combinations
> >> class(a) # it's a "matrix" "array"
> >>
> >> now hypothetical data of three matrix for further calculation:
> >> pmat<- matrix(1:16, nrow = 4)
> >> gmat<- matrix(17:32, nrow = 4)
> >> wmat<- matrix(1:4, nrow = 4)
> >>
> >> My custom function for further calculations:
> >> selection.index<- function(ID, phen_mat, gen_mat, weight_mat, GAY){
> >>ID = toString(ID)
> >>p<- as.matrix(phen_mat)
> >>g<- as.matrix(gen_mat)
> >>w<- as.matrix(weight_mat)
> >>bmat<- solve(phen_mat) %*% gen_mat %*% weight_mat
> >>GA<- 2.063 * t(bmat) %*% g %*% w / (t(bmat) %*% p %*% bmat)^0.5
> >>PRE<- if(missing(GAY)){
> >>  (GA/GA) * 100
> >>} else {
> >>  (GA/GAY) * 100
> >>}
> >>result<- list("ID" = ID, "b" = matrix(round(bmat,4), nrow = 1), "GA" = 
> >> round(GA,4), "PRE" = round(PRE,4))
> >>return(data.frame(result))
> >> }
> >>
> >> Now I want to store this data into a list for further calculation:
> >> sc<- list()
> >> sc[[1]]<- selection.index(ID = 12, phen_mat = pmat[c(1,2),c(1,2)], gen_mat 
> >> = gmat[c(1,2),c(1,2)], weight_mat = wmat[c(1,2),1])
> >> sc[[2]]<- selection.index(ID = 13, phen_mat = pmat[c(1,3),c(1,3)], gen_mat 
> >> = gmat[c(1,3),c(1,3)], weight_mat = wmat[c(1,3),1])
> >> sc[[3]]<- selection.index(ID = 14, phen_mat = pmat[c(1,4),c(1,4)], gen_mat 
> >> = gmat[c(1,4),c(1,4)], weight_mat = wmat[c(1,4),1])
> >> sc[[4]]<- selection.index(ID = 23, phen_mat = pmat[c(2,3),c(2,3)], gen_mat 
> >> = gmat[c(2,3),c(2,3)], weight_mat = wmat[c(2,3),1])
> >> sc[[5]]<- selection.index(ID = 24, phen_mat = pmat[c(2,4),c(2,4)], gen_mat 
> >> = gmat[c(2,4),c(2,4)], weight_mat = wmat[c(2,4),1])
> >> sc[[6]]<- selection.index(ID = 34, phen_mat = pmat[c(3,4),c(3,4)], gen_mat 
> >> = gmat[c(3,4),c(3,4)], weight_mat = wmat[c(3,4),1])
> >> above list code is monotonous and time consuming for large data 
> >> combination cycles like (7,2) = 21 combinations, (10,2) = 45 combinations. 
> >> So I want to use the matrix a's each row as a vector in the 
> >> selection.index function and result stores in a list.
> >>
> >> I hope now you will understand the full problem. I have checked the 
> >> selection.index which has no issues and works well.
> >> Thank you.
> >>
> >
> > __
> > 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 

Re: [R] for loop implementation in below problem

2021-03-22 Thread Duncan Murdoch

On 22/03/2021 1:59 a.m., Jim Lemon wrote:

Hi Goyani,
You are setting "PRE" to the return value of "if" which is one of TRUE
(1), FALSE(0) or NULL. 


That's not true at all.  The statement was

PRE<- if(missing(GAY)){
  (GA/GA) * 100
} else {
  (GA/GAY) * 100
}

so the result is (GA/GA) * 100 or (GA/GAY)*100.


Because GAY is always missing in your example,


If that's true and GA isn't missing, the result will always be 100.

Duncan Murdoch


"PRE" is always set to 1. Then you always want to pass 1 in the sample
list, and that will not assign anything to PRE. By correcting the "if"
clause and defining matrices that are unlikely to be singular, I can
run a "for" loop as follows:

selection.index<- function(ID, phen_mat, gen_mat, weight_mat, GAY){
  p<-as.matrix(phen_mat)
  g<-as.matrix(gen_mat)
  w<-as.matrix(weight_mat)
  bmat<- solve(phen_mat) %*% gen_mat %*% weight_mat
  GA<- 2.063 * t(bmat) %*% g %*% w / (t(bmat) %*% p %*% bmat)^0.5
  if(missing(GAY)) PRE<-(GA/GA) * 100
  else PRE<-(GA/GAY) * 100
  result<-list(ID=ID,b=matrix(round(bmat,4),nrow=1),
   GA=round(GA,4),PRE=round(PRE,4))
  return(data.frame(result))
}

pmat<-matrix(sample(1:16,16),4)
gmat<-matrix(sample(17:32),16,4)
wmat<-matrix(sample(1:4,4),4)

mi<-combn(1:4,2)
sc<-list()
for(i in 1:ncol(matindx)) {
  as.numeric(ID<-paste0(mi[,i]))
  sc[[i]]<-selection.index(ID,pmat[mi[,i],mi[,i]],gmat[mi[,i],mi[,i]],
   wmat[mi[,i]],1)
}

This produces output for me. Good luck with whatever you are doing with this.

Jim





On Mon, Mar 22, 2021 at 2:51 PM Goyani Zankrut  wrote:


Greetings of the day,
Thank you for your response, Sir.
The full problem statement is given below:

In our case, I'm taking 4 traits.
library(arrangements)
a<- combinations(4,2) # gives 6 pairwise combinations
class(a) # it's a "matrix" "array"

now hypothetical data of three matrix for further calculation:
pmat<- matrix(1:16, nrow = 4)
gmat<- matrix(17:32, nrow = 4)
wmat<- matrix(1:4, nrow = 4)

My custom function for further calculations:
selection.index<- function(ID, phen_mat, gen_mat, weight_mat, GAY){
   ID = toString(ID)
   p<- as.matrix(phen_mat)
   g<- as.matrix(gen_mat)
   w<- as.matrix(weight_mat)
   bmat<- solve(phen_mat) %*% gen_mat %*% weight_mat
   GA<- 2.063 * t(bmat) %*% g %*% w / (t(bmat) %*% p %*% bmat)^0.5
   PRE<- if(missing(GAY)){
 (GA/GA) * 100
   } else {
 (GA/GAY) * 100
   }
   result<- list("ID" = ID, "b" = matrix(round(bmat,4), nrow = 1), "GA" = round(GA,4), 
"PRE" = round(PRE,4))
   return(data.frame(result))
}

Now I want to store this data into a list for further calculation:
sc<- list()
sc[[1]]<- selection.index(ID = 12, phen_mat = pmat[c(1,2),c(1,2)], gen_mat = 
gmat[c(1,2),c(1,2)], weight_mat = wmat[c(1,2),1])
sc[[2]]<- selection.index(ID = 13, phen_mat = pmat[c(1,3),c(1,3)], gen_mat = 
gmat[c(1,3),c(1,3)], weight_mat = wmat[c(1,3),1])
sc[[3]]<- selection.index(ID = 14, phen_mat = pmat[c(1,4),c(1,4)], gen_mat = 
gmat[c(1,4),c(1,4)], weight_mat = wmat[c(1,4),1])
sc[[4]]<- selection.index(ID = 23, phen_mat = pmat[c(2,3),c(2,3)], gen_mat = 
gmat[c(2,3),c(2,3)], weight_mat = wmat[c(2,3),1])
sc[[5]]<- selection.index(ID = 24, phen_mat = pmat[c(2,4),c(2,4)], gen_mat = 
gmat[c(2,4),c(2,4)], weight_mat = wmat[c(2,4),1])
sc[[6]]<- selection.index(ID = 34, phen_mat = pmat[c(3,4),c(3,4)], gen_mat = 
gmat[c(3,4),c(3,4)], weight_mat = wmat[c(3,4),1])
above list code is monotonous and time consuming for large data combination 
cycles like (7,2) = 21 combinations, (10,2) = 45 combinations. So I want to use 
the matrix a's each row as a vector in the selection.index function and result 
stores in a list.

I hope now you will understand the full problem. I have checked the 
selection.index which has no issues and works well.
Thank you.



__
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] for loop implementation in below problem

2021-03-21 Thread Jim Lemon
Hi Goyani,
You are setting "PRE" to the return value of "if" which is one of TRUE
(1), FALSE(0) or NULL. Because GAY is always missing in your example,
"PRE" is always set to 1. Then you always want to pass 1 in the sample
list, and that will not assign anything to PRE. By correcting the "if"
clause and defining matrices that are unlikely to be singular, I can
run a "for" loop as follows:

selection.index<- function(ID, phen_mat, gen_mat, weight_mat, GAY){
 p<-as.matrix(phen_mat)
 g<-as.matrix(gen_mat)
 w<-as.matrix(weight_mat)
 bmat<- solve(phen_mat) %*% gen_mat %*% weight_mat
 GA<- 2.063 * t(bmat) %*% g %*% w / (t(bmat) %*% p %*% bmat)^0.5
 if(missing(GAY)) PRE<-(GA/GA) * 100
 else PRE<-(GA/GAY) * 100
 result<-list(ID=ID,b=matrix(round(bmat,4),nrow=1),
  GA=round(GA,4),PRE=round(PRE,4))
 return(data.frame(result))
}

pmat<-matrix(sample(1:16,16),4)
gmat<-matrix(sample(17:32),16,4)
wmat<-matrix(sample(1:4,4),4)

mi<-combn(1:4,2)
sc<-list()
for(i in 1:ncol(matindx)) {
 as.numeric(ID<-paste0(mi[,i]))
 sc[[i]]<-selection.index(ID,pmat[mi[,i],mi[,i]],gmat[mi[,i],mi[,i]],
  wmat[mi[,i]],1)
}

This produces output for me. Good luck with whatever you are doing with this.

Jim





On Mon, Mar 22, 2021 at 2:51 PM Goyani Zankrut  wrote:
>
> Greetings of the day,
> Thank you for your response, Sir.
> The full problem statement is given below:
>
> In our case, I'm taking 4 traits.
> library(arrangements)
> a<- combinations(4,2) # gives 6 pairwise combinations
> class(a) # it's a "matrix" "array"
>
> now hypothetical data of three matrix for further calculation:
> pmat<- matrix(1:16, nrow = 4)
> gmat<- matrix(17:32, nrow = 4)
> wmat<- matrix(1:4, nrow = 4)
>
> My custom function for further calculations:
> selection.index<- function(ID, phen_mat, gen_mat, weight_mat, GAY){
>   ID = toString(ID)
>   p<- as.matrix(phen_mat)
>   g<- as.matrix(gen_mat)
>   w<- as.matrix(weight_mat)
>   bmat<- solve(phen_mat) %*% gen_mat %*% weight_mat
>   GA<- 2.063 * t(bmat) %*% g %*% w / (t(bmat) %*% p %*% bmat)^0.5
>   PRE<- if(missing(GAY)){
> (GA/GA) * 100
>   } else {
> (GA/GAY) * 100
>   }
>   result<- list("ID" = ID, "b" = matrix(round(bmat,4), nrow = 1), "GA" = 
> round(GA,4), "PRE" = round(PRE,4))
>   return(data.frame(result))
> }
>
> Now I want to store this data into a list for further calculation:
> sc<- list()
> sc[[1]]<- selection.index(ID = 12, phen_mat = pmat[c(1,2),c(1,2)], gen_mat = 
> gmat[c(1,2),c(1,2)], weight_mat = wmat[c(1,2),1])
> sc[[2]]<- selection.index(ID = 13, phen_mat = pmat[c(1,3),c(1,3)], gen_mat = 
> gmat[c(1,3),c(1,3)], weight_mat = wmat[c(1,3),1])
> sc[[3]]<- selection.index(ID = 14, phen_mat = pmat[c(1,4),c(1,4)], gen_mat = 
> gmat[c(1,4),c(1,4)], weight_mat = wmat[c(1,4),1])
> sc[[4]]<- selection.index(ID = 23, phen_mat = pmat[c(2,3),c(2,3)], gen_mat = 
> gmat[c(2,3),c(2,3)], weight_mat = wmat[c(2,3),1])
> sc[[5]]<- selection.index(ID = 24, phen_mat = pmat[c(2,4),c(2,4)], gen_mat = 
> gmat[c(2,4),c(2,4)], weight_mat = wmat[c(2,4),1])
> sc[[6]]<- selection.index(ID = 34, phen_mat = pmat[c(3,4),c(3,4)], gen_mat = 
> gmat[c(3,4),c(3,4)], weight_mat = wmat[c(3,4),1])
> above list code is monotonous and time consuming for large data combination 
> cycles like (7,2) = 21 combinations, (10,2) = 45 combinations. So I want to 
> use the matrix a's each row as a vector in the selection.index function and 
> result stores in a list.
>
> I hope now you will understand the full problem. I have checked the 
> selection.index which has no issues and works well.
> Thank you.
>

__
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] for loop implementation in below problem

2021-03-21 Thread Jim Lemon
Hi Goyani,
In its present form, the function stalls because you haven't defined
pmat before trying to pass it to the function. gmat and wmat suffered
the same fate. Even if I define these matrices as I think you have,
"solve" fails because at least one is singular. First, put the
function in order as below. I think this is what you sent made
readable.

selection.index<- function(ID, phen_mat, gen_mat, weight_mat, GAY){
 ID<-toString(ID)
 p<-as.matrix(phen_mat)
 g<-as.matrix(gen_mat)
 w<-as.matrix(weight_mat)
 bmat<- solve(phen_mat) %*% gen_mat %*% weight_mat
 GA<- 2.063 * t(bmat) %*% g %*% w / (t(bmat) %*% p %*% bmat)^0.5
 if(missing(GAY)) PRE<-(GA/GA) * 100
 else PRE<-(GA/GAY) * 100
 result<-list(ID=ID,b=matrix(round(bmat,4),nrow=1),
  GA=round(GA,4),PRE=round(PRE,4))
 return(data.frame(result))
}

Next, what sort of matrices do you want to pass? Then an answer may emerge.

Jim

On Mon, Mar 22, 2021 at 6:03 AM Goyani Zankrut  wrote:
>
> I created custom function according to my requirement which is given below:
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> *selection.index<- function(ID, phen_mat, gen_mat, weight_mat, GAY){  ID =
> toString(ID)  p<- as.matrix(phen_mat)  g<- as.matrix(gen_mat)  w<-
> as.matrix(weight_mat)  bmat<- solve(phen_mat) %*% gen_mat %*% weight_mat
> GA<- 2.063 * t(bmat) %*% g %*% w / (t(bmat) %*% p %*% bmat)^0.5  PRE<-
> if(missing(GAY)){(GA/GA) * 100  } else {(GA/GAY) * 100  }  result<-
> list("ID" = ID, "b" = matrix(round(bmat,4), nrow = 1), "GA" = round(GA,4),
> "PRE" = round(PRE,4))  return(data.frame(result))}*
>
> *sc<- list()*
> *sc[[1]]<- selection.index(ID = 12, pmat[1:2,1:2], gmat[1:2,1:2],
> wmat[1:2,1])*
> *sc[[2]]<- selection.index(ID = 13, pmat[c(1,3),c(1,3)],
> gmat[c(1,3),c(1,3)], wmat[c(1,3),1])*
>
> for more detail about question follow stack overflow link:
> https://stackoverflow.com/questions/66734928/how-to-solve-this-through-loop
> *"Healthy soil, Healthy life."*
> *"A war based on Satyagraha is always of two kinds. One is the war we wage
> against injustice, and the other we fight our won weaknesses."* - *Sardar
> Patel*
> *"You have to dream before your dreams can come true."* - *A. P. J.* *Abdul
> Kalam*
> *"Think before you print and save a tree."*
>
> *ZANKRUT GOYANI*
> *B.Sc. (Hons.) Agriculture*
>
> [[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.


[R] for loop implementation in below problem

2021-03-21 Thread Goyani Zankrut
I created custom function according to my requirement which is given below:














*selection.index<- function(ID, phen_mat, gen_mat, weight_mat, GAY){  ID =
toString(ID)  p<- as.matrix(phen_mat)  g<- as.matrix(gen_mat)  w<-
as.matrix(weight_mat)  bmat<- solve(phen_mat) %*% gen_mat %*% weight_mat
GA<- 2.063 * t(bmat) %*% g %*% w / (t(bmat) %*% p %*% bmat)^0.5  PRE<-
if(missing(GAY)){(GA/GA) * 100  } else {(GA/GAY) * 100  }  result<-
list("ID" = ID, "b" = matrix(round(bmat,4), nrow = 1), "GA" = round(GA,4),
"PRE" = round(PRE,4))  return(data.frame(result))}*

*sc<- list()*
*sc[[1]]<- selection.index(ID = 12, pmat[1:2,1:2], gmat[1:2,1:2],
wmat[1:2,1])*
*sc[[2]]<- selection.index(ID = 13, pmat[c(1,3),c(1,3)],
gmat[c(1,3),c(1,3)], wmat[c(1,3),1])*

for more detail about question follow stack overflow link:
https://stackoverflow.com/questions/66734928/how-to-solve-this-through-loop
*"Healthy soil, Healthy life."*
*"A war based on Satyagraha is always of two kinds. One is the war we wage
against injustice, and the other we fight our won weaknesses."* - *Sardar
Patel*
*"You have to dream before your dreams can come true."* - *A. P. J.* *Abdul
Kalam*
*"Think before you print and save a tree."*

*ZANKRUT GOYANI*
*B.Sc. (Hons.) Agriculture*

[[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] R for-loop to add layer to lattice plot

2020-10-28 Thread Luigi Marongiu
Awesome, thanks!

On Wed, Oct 28, 2020 at 7:00 AM Deepayan Sarkar
 wrote:
>
> On Tue, Oct 27, 2020 at 6:04 PM Luigi Marongiu  
> wrote:
> >
> > Hello,
> > I am using e1071 to run support vector machine. I would like to plot
> > the data with lattice and specifically show the hyperplanes created by
> > the system.
> > I can store the hyperplane as a contour in an object, and I can plot
> > one object at a time. Since there will be thousands of elements to
> > plot, I can't manually add them one by one to the plot, so I tried to
> > loop into them, but only the last is added.
> > Here it the working example for more clarity:
> >
> > ```
> > library(e1071)
> > library(lattice)
> > library(latticeExtra)
> >
> > make.grid <- function(x, n = 1000) {
> >   grange = apply(x, 2, range)
> >   x1 = seq(from = grange[1,1], to = grange[2,1], length = n)
> >   x2 = seq(from = grange[1,2], to = grange[2,2], length = n)
> >   expand.grid(X1 = x1, X2 = x2)
> > }
> >
> > plot_list <- list()
> > for (i in 1:10) {
> >   x1 = rnorm(100, mean = 0.2, sd = 0.15)
> >   y1 = rnorm(100, mean = 0.7, sd = 0.15)
> >   y2 = rnorm(100, mean = 0.2, sd = 0.15)
> >   x2 = rnorm(100, mean = 0.75, sd = 0.15)
> >   df = data.frame(x = c(x1,x2), y=c(y1,y2),
> >   z=c(rep(0, length(x1)), rep(1, length(x2
> >   df$z = factor(c(rep(0, length(x1)), rep(1, length(x2
> >   df[, "train"] <- ifelse(runif(nrow(df)) < 0.8, 1, 0)
> >   trainset <- df[df$train == 1, ]
> >   testset <- df[df$train == 0, ]
> >   trainColNum <- grep("train", names(df))
> >   trainset <- trainset[, -trainColNum]
> >   testset <- testset[, -trainColNum]
> >   svm_model <- svm(z ~ .,
> >   data = trainset,
> >   type = "C-classification",
> >   kernel = "linear",
> >   scale = FALSE)
> >   # generate contour
> >   xmat = make.grid(matrix(c(testset$x, testset$y),
> >   ncol = 2, byrow=FALSE))
> >   xgrid = as.data.frame(xmat)
> >   names(xgrid) = c("x", "y")
> >   z = predict(svm_model, xgrid)
> >   xyz_dat = as.data.frame(cbind(xgrid, z))
> >   plot_list[[i]] = contourplot(z ~ y+x, data=xyz_dat, pretty = TRUE,
> >xlim=c(-1,50), ylim=c(-0.001, 0.05),
> >labels = FALSE, col = "blue", lwd = 0.5)
> >
> > }
> > # the contour is stored in the object plot_list
> > str(plot_list) # confirm that there is data here
> >
> > # I can add one element at the time to lattice's xyplot and store it
> > in an object P
> > P = xyplot(y ~ x, group = z, data = df,
> >pch = 16, cex = 1.5, alpha = 0.25) + as.layer(plot_list[[1]]) +
> >   as.layer(plot_list[[2]])
> > plot(P)  # this demonstrates that the lines are not the same
> >
> > # but if I add the elements via loop, it does not work
> > for (i in 1:length(plot_list)) {
> >   print(i)
> >   P = xyplot(y ~ x, group = z, data = df,
> >  pch = 16, cex = 1.5, alpha = 0.25) + as.layer(plot_list[[i]])
> > }
> > plot(P)
> > ```
> >
> > Am I missing something?
>
> Yes, as Mark says, you need to change the last part to something like
>
> P = xyplot(y ~ x, group = z, data = df, pch = 16, cex = 1.5, alpha = 0.25)
> for (i in 1:length(plot_list)) {
>   print(i)
>   P = P + as.layer(plot_list[[i]])
> }
> plot(P)
>
> -Deepayan
>
> > Thank you
> >
> > __
> > 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.



-- 
Best regards,
Luigi

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] R for-loop to add layer to lattice plot

2020-10-28 Thread Deepayan Sarkar
On Tue, Oct 27, 2020 at 6:04 PM Luigi Marongiu  wrote:
>
> Hello,
> I am using e1071 to run support vector machine. I would like to plot
> the data with lattice and specifically show the hyperplanes created by
> the system.
> I can store the hyperplane as a contour in an object, and I can plot
> one object at a time. Since there will be thousands of elements to
> plot, I can't manually add them one by one to the plot, so I tried to
> loop into them, but only the last is added.
> Here it the working example for more clarity:
>
> ```
> library(e1071)
> library(lattice)
> library(latticeExtra)
>
> make.grid <- function(x, n = 1000) {
>   grange = apply(x, 2, range)
>   x1 = seq(from = grange[1,1], to = grange[2,1], length = n)
>   x2 = seq(from = grange[1,2], to = grange[2,2], length = n)
>   expand.grid(X1 = x1, X2 = x2)
> }
>
> plot_list <- list()
> for (i in 1:10) {
>   x1 = rnorm(100, mean = 0.2, sd = 0.15)
>   y1 = rnorm(100, mean = 0.7, sd = 0.15)
>   y2 = rnorm(100, mean = 0.2, sd = 0.15)
>   x2 = rnorm(100, mean = 0.75, sd = 0.15)
>   df = data.frame(x = c(x1,x2), y=c(y1,y2),
>   z=c(rep(0, length(x1)), rep(1, length(x2
>   df$z = factor(c(rep(0, length(x1)), rep(1, length(x2
>   df[, "train"] <- ifelse(runif(nrow(df)) < 0.8, 1, 0)
>   trainset <- df[df$train == 1, ]
>   testset <- df[df$train == 0, ]
>   trainColNum <- grep("train", names(df))
>   trainset <- trainset[, -trainColNum]
>   testset <- testset[, -trainColNum]
>   svm_model <- svm(z ~ .,
>   data = trainset,
>   type = "C-classification",
>   kernel = "linear",
>   scale = FALSE)
>   # generate contour
>   xmat = make.grid(matrix(c(testset$x, testset$y),
>   ncol = 2, byrow=FALSE))
>   xgrid = as.data.frame(xmat)
>   names(xgrid) = c("x", "y")
>   z = predict(svm_model, xgrid)
>   xyz_dat = as.data.frame(cbind(xgrid, z))
>   plot_list[[i]] = contourplot(z ~ y+x, data=xyz_dat, pretty = TRUE,
>xlim=c(-1,50), ylim=c(-0.001, 0.05),
>labels = FALSE, col = "blue", lwd = 0.5)
>
> }
> # the contour is stored in the object plot_list
> str(plot_list) # confirm that there is data here
>
> # I can add one element at the time to lattice's xyplot and store it
> in an object P
> P = xyplot(y ~ x, group = z, data = df,
>pch = 16, cex = 1.5, alpha = 0.25) + as.layer(plot_list[[1]]) +
>   as.layer(plot_list[[2]])
> plot(P)  # this demonstrates that the lines are not the same
>
> # but if I add the elements via loop, it does not work
> for (i in 1:length(plot_list)) {
>   print(i)
>   P = xyplot(y ~ x, group = z, data = df,
>  pch = 16, cex = 1.5, alpha = 0.25) + as.layer(plot_list[[i]])
> }
> plot(P)
> ```
>
> Am I missing something?

Yes, as Mark says, you need to change the last part to something like

P = xyplot(y ~ x, group = z, data = df, pch = 16, cex = 1.5, alpha = 0.25)
for (i in 1:length(plot_list)) {
  print(i)
  P = P + as.layer(plot_list[[i]])
}
plot(P)

-Deepayan

> Thank you
>
> __
> 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] R for-loop to add layer to lattice plot

2020-10-27 Thread Mark Leeds
Hi: I think you're writing over the plots so only the last one exists.
Maybe try P = P + whatever but
I'm not sure if that's allowed with plots.



On Tue, Oct 27, 2020 at 8:34 AM Luigi Marongiu 
wrote:

> Hello,
> I am using e1071 to run support vector machine. I would like to plot
> the data with lattice and specifically show the hyperplanes created by
> the system.
> I can store the hyperplane as a contour in an object, and I can plot
> one object at a time. Since there will be thousands of elements to
> plot, I can't manually add them one by one to the plot, so I tried to
> loop into them, but only the last is added.
> Here it the working example for more clarity:
>
> ```
> library(e1071)
> library(lattice)
> library(latticeExtra)
>
> make.grid <- function(x, n = 1000) {
>   grange = apply(x, 2, range)
>   x1 = seq(from = grange[1,1], to = grange[2,1], length = n)
>   x2 = seq(from = grange[1,2], to = grange[2,2], length = n)
>   expand.grid(X1 = x1, X2 = x2)
> }
>
> plot_list <- list()
> for (i in 1:10) {
>   x1 = rnorm(100, mean = 0.2, sd = 0.15)
>   y1 = rnorm(100, mean = 0.7, sd = 0.15)
>   y2 = rnorm(100, mean = 0.2, sd = 0.15)
>   x2 = rnorm(100, mean = 0.75, sd = 0.15)
>   df = data.frame(x = c(x1,x2), y=c(y1,y2),
>   z=c(rep(0, length(x1)), rep(1, length(x2
>   df$z = factor(c(rep(0, length(x1)), rep(1, length(x2
>   df[, "train"] <- ifelse(runif(nrow(df)) < 0.8, 1, 0)
>   trainset <- df[df$train == 1, ]
>   testset <- df[df$train == 0, ]
>   trainColNum <- grep("train", names(df))
>   trainset <- trainset[, -trainColNum]
>   testset <- testset[, -trainColNum]
>   svm_model <- svm(z ~ .,
>   data = trainset,
>   type = "C-classification",
>   kernel = "linear",
>   scale = FALSE)
>   # generate contour
>   xmat = make.grid(matrix(c(testset$x, testset$y),
>   ncol = 2, byrow=FALSE))
>   xgrid = as.data.frame(xmat)
>   names(xgrid) = c("x", "y")
>   z = predict(svm_model, xgrid)
>   xyz_dat = as.data.frame(cbind(xgrid, z))
>   plot_list[[i]] = contourplot(z ~ y+x, data=xyz_dat, pretty = TRUE,
>xlim=c(-1,50), ylim=c(-0.001, 0.05),
>labels = FALSE, col = "blue", lwd = 0.5)
>
> }
> # the contour is stored in the object plot_list
> str(plot_list) # confirm that there is data here
>
> # I can add one element at the time to lattice's xyplot and store it
> in an object P
> P = xyplot(y ~ x, group = z, data = df,
>pch = 16, cex = 1.5, alpha = 0.25) + as.layer(plot_list[[1]]) +
>   as.layer(plot_list[[2]])
> plot(P)  # this demonstrates that the lines are not the same
>
> # but if I add the elements via loop, it does not work
> for (i in 1:length(plot_list)) {
>   print(i)
>   P = xyplot(y ~ x, group = z, data = df,
>  pch = 16, cex = 1.5, alpha = 0.25) + as.layer(plot_list[[i]])
> }
> plot(P)
> ```
>
> Am I missing something?
> Thank you
>
> __
> 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] R for-loop to add layer to lattice plot

2020-10-27 Thread Luigi Marongiu
Hello,
I am using e1071 to run support vector machine. I would like to plot
the data with lattice and specifically show the hyperplanes created by
the system.
I can store the hyperplane as a contour in an object, and I can plot
one object at a time. Since there will be thousands of elements to
plot, I can't manually add them one by one to the plot, so I tried to
loop into them, but only the last is added.
Here it the working example for more clarity:

```
library(e1071)
library(lattice)
library(latticeExtra)

make.grid <- function(x, n = 1000) {
  grange = apply(x, 2, range)
  x1 = seq(from = grange[1,1], to = grange[2,1], length = n)
  x2 = seq(from = grange[1,2], to = grange[2,2], length = n)
  expand.grid(X1 = x1, X2 = x2)
}

plot_list <- list()
for (i in 1:10) {
  x1 = rnorm(100, mean = 0.2, sd = 0.15)
  y1 = rnorm(100, mean = 0.7, sd = 0.15)
  y2 = rnorm(100, mean = 0.2, sd = 0.15)
  x2 = rnorm(100, mean = 0.75, sd = 0.15)
  df = data.frame(x = c(x1,x2), y=c(y1,y2),
  z=c(rep(0, length(x1)), rep(1, length(x2
  df$z = factor(c(rep(0, length(x1)), rep(1, length(x2
  df[, "train"] <- ifelse(runif(nrow(df)) < 0.8, 1, 0)
  trainset <- df[df$train == 1, ]
  testset <- df[df$train == 0, ]
  trainColNum <- grep("train", names(df))
  trainset <- trainset[, -trainColNum]
  testset <- testset[, -trainColNum]
  svm_model <- svm(z ~ .,
  data = trainset,
  type = "C-classification",
  kernel = "linear",
  scale = FALSE)
  # generate contour
  xmat = make.grid(matrix(c(testset$x, testset$y),
  ncol = 2, byrow=FALSE))
  xgrid = as.data.frame(xmat)
  names(xgrid) = c("x", "y")
  z = predict(svm_model, xgrid)
  xyz_dat = as.data.frame(cbind(xgrid, z))
  plot_list[[i]] = contourplot(z ~ y+x, data=xyz_dat, pretty = TRUE,
   xlim=c(-1,50), ylim=c(-0.001, 0.05),
   labels = FALSE, col = "blue", lwd = 0.5)

}
# the contour is stored in the object plot_list
str(plot_list) # confirm that there is data here

# I can add one element at the time to lattice's xyplot and store it
in an object P
P = xyplot(y ~ x, group = z, data = df,
   pch = 16, cex = 1.5, alpha = 0.25) + as.layer(plot_list[[1]]) +
  as.layer(plot_list[[2]])
plot(P)  # this demonstrates that the lines are not the same

# but if I add the elements via loop, it does not work
for (i in 1:length(plot_list)) {
  print(i)
  P = xyplot(y ~ x, group = z, data = df,
 pch = 16, cex = 1.5, alpha = 0.25) + as.layer(plot_list[[i]])
}
plot(P)
```

Am I missing something?
Thank you

__
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] FW: Loop for two columns and 154 rows

2020-09-15 Thread PIKAL Petr
Sorry, forgot to copy to r help.

Petr
> -Original Message-
> From: PIKAL Petr
> Sent: Tuesday, September 15, 2020 11:53 AM
> To: 'Hesham A. AL-bukhaiti' 
> Subject: RE: [R] Loop for two columns and 154 rows
> 
> Hi
> 
> Your mail is unreadable, post in plain text not HTML.
> 
> If I deciphered it correcttly you want all values which have G1 in column 1 
> and
> G2 in column 2 or G2 in column 1 and G1 in column to produce 1 all other
> produce 0
> 
> So if your data frame is named truth
> 
> truth$column3 <- ((truth[,1] =="G1" & truth[,2] =="G2") | (truth[,2] =="G1" &
> truth[,1] =="G2")) * 1
> 
> Cheers
> Petr
> 
> > -Original Message-
> > From: R-help  On Behalf Of Hesham A. AL-
> > bukhaiti via R-help
> > Sent: Tuesday, September 15, 2020 11:01 AM
> > To: r-help@r-project.org
> > Subject: [R] Loop for two columns and 154 rows
> >
> >  Dears in R :i have this code in R:
> > # this for do not work true (i tried )out<-read.csv("outbr.csv") truth<-
> > out[,seq(1,2)]truth<-
> > cbind(as.character(truth[,1]),as.character(truth[,2])
> ,as.data.frame(rep(
> > 0,,dim(out)[1])));for (j in 1:2) {  for (i in 1:20) {truth[(truth[,1]== 
> > truth[j,i] &
> > truth[,2]== truth[j,i+1]) | (truth[,1]== truth[j+1,i] & truth[,2]==
> > truth[j+1,i+1]),3]<-1   } }
> > #truth<-out[,seq(1,2)]#truth<-
> > cbind(as.character(truth[,1]),as.character(truth[,2])  #
> ,as.data.frame(rep
> > (0,,dim(out)[1])));#truth[(truth[,1]=="G2" & truth[,2]=="G1") |
> (truth[,1]=="G1"
> > & truth[,2]=="G2"),3]<-1
> >
> #
> > #3
> >
> > I have file have two columns  . data in this file is text just (G1,G2,G3… to
> > G154). one element  can repeat, no problem ,so  we have 23562 rows in two
> > columns (for 154 elements) like :
> > Column1   column2 column3
> > G1 G40
> > G4 G60
> > G100   G7 1G7  G100. 1. 
> >  ..   .
> I
> > want to make third column (1 or 0) based on this condition:
> > IF  truth[,1]==”G1” & truth[,2]==”G2” | truth[,1]==”G2” & truth[,2]==”G1” <-
> > 1.then In the third column write 1 otherwise write 0.G1 and G2  just
> > exampl  (indeed  i want test If two each elements   has a reciprocal
> > relationship(G1 to G2 and G2 to G1or not) Best regHesham
> >
> >
> >
> >
> > [[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.


[R-es] loop-for

2020-06-04 Thread Manuel Mendoza
Buenos días ¿Alguien sabe por qué en este loop, si hago, p.e., i = 1 y
corro las dos últimas filas me lo hace bien (con "frg"), pero si corro todo
el loop me abre 12 ventanas, en vez de 10 (la dimensión del vector
predictores) y además vacías?

predictores <- c("frg","omn","bc","co","pr","gg","fg","mf","br","hc")
  for(i in 1:length(predictores)){
windows()
partial(RFfit, pred.var = predictores[i], which.class = "Ard", plot = T,
 prob = T, chull=T, type="classification",plot.engine =
"ggplot2", rug=T)
  }

Gracias,
Manuel

[[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] [R ] Writing loop to estimate ARCH test for a multiple columns of a data frame?

2020-05-13 Thread Subhamitra Patra
Dear Sir,

I am so sorry that due to certain inconveniences, I became late to try your
suggested code and to reply to your email.

Thank you very much for your wonderful solution and suggestion for my
problem. Like before,  Your suggested code has worked awesome. Even, I
successfully imported the required output to the word following your
suggested similar path for the Libre office editor.

But, I have certain queries on your suggested code mentioned below which I
would like to discuss with you for my further learning.

1. Is there any difference between reading the tab and text file in R
because when I used  sp_8_5<-read.table("sp_8_5.tab",sep="\t",


header=TRUE,stringsAsFactors=FALSE)
it had thrown some error. But, when I changed the sp_8_5.tab into
sp_8_5.text, it worked. So, here my query, "does R read tab and text file
differently, however, both the files are similar"?

2. In the code, "return(sprintf("ChiSq = %.1f, p =
%.3f",archout$statistic,archout$p.value))", sprintf stands for printing the
particular results (i.e., statistics and p-value), right? Further, "ChiSq =
%.1f, p = %.3f" indicate the calling the values up to 1 and 3 decimal
points respectively, right? kindly correct me if I am worng in my
interpretation.

3. While opening a text file, sink("sp_8_5.txt")
 for(row in 0:2) {
 for(column in 1:4)

cat(spout[[column+row*4]],ifelse(column
< 4,"\t","\n"))
 }
   sink()
3.1. what sink indicates, I think here sink calls for the arranging of the
statistics and p-values in the required 3*4 dimension in the generated text
file, right? Please educate me.
3.2 Hence, the results are arranged in 3 rows and 4 columns in the text
file. I understand the code for arranging loop for columns [i.e.,
for(column in 1:4) ], but i didn't understand the loop for row [i.e., for(row
in 0:2)]. In particular, what is the logic behind the setting of 2 rather
than 3 for 3 rows in "for(row in 0:2)"?
3.3. In the code, "cat(spout[[column+row*4]],ifelse(column <
4,"\t","\n"))", what cat indicates? what is the logic behind [column+row*4]
 and ifelse(column < 4,"\t","\n") ? This is my major query in the entire
code. Please help me to understand this line.


Along with the above queries in your suggested code, I have one more query that
is it possible to rename each row and column? Actually, why I am asking
this because I have data from 80 countries, and each country has 5 columns
of data arranging in 5 columns. In other words, the total number of columns
in my study is 400. While doing the ARCH test for each column, there may be
a mistake to arrange the results in the text file. Thus, I want to arrange
the resulted statistics for 5 columns (for instance A1, A2, A3, A4, A5) for
each country in the following way which I think will definitely avoid any
kind of typo-mistake in arranging output in the text file. In other words,
Each row will have results for each country arranged in 5 columns for the
particular 5 variables which help to identify the particular result for the
particular columns of the particular countries in an easy manner.


Country   A1A2   A3 A4 A5
India  0.65  0.33   0.32   0.12  0.34
Israel  0.35  0.05   0.100.15   0.23
Australia  0.43  0.250.450.550.56

and so on.


Thank you very much, Sir, for educating a R learner for which I shall be
always grateful to you.


[image: Mailtrack]

Sender
notified by
Mailtrack

05/13/20,
04:56:34 PM

On Sat, May 9, 2020 at 8:58 AM Jim Lemon  wrote:

> Hi Subhamitra,
> I have washed the dishes and had a night's sleep, so I can now deal with
> your text munging problem. First, I'll reiterate the solution I sent:
>
> sp_8_5<-read.table("sp_8_5.tab",sep="\t",
>  header=TRUE,stringsAsFactors=FALSE)
> library(tseries)
> library(FinTS)
> # create a function that returns only the
> # statistic and p.value as a string
> archStatP<-function(x) {
>  archout<-ArchTest(x)
>  # I have truncated the values here
>  return(sprintf("ChiSq = %.1f, p =
> %.3f",archout$statistic,archout$p.value))
> }
> # using "lapply", run the test on each column
> spout<-lapply(sp_8_5[,2:13],archStatP)
>
> If you look at "spout" you will see that it is a list of 12 character
> strings. I arranged this as you seem to want the contents of a 3x4 table in
> a document. This is one way to do it, there are others.
>
> First, create a text table of the desired dimensions. I'll do it with
> loops as you seem to be familiar with them:
>
> # open a text file
> sink("sp_8_5.txt")
> for(row in 0:2) {
>  for(column in 1:4)
>   cat(spout[[column+row*4]],ifelse(column < 4,"\t","\n"))
> }
> sink()
>
> If you 

Re: [R] [R ] Writing loop to estimate ARCH test for a multiple columns of a data frame?

2020-05-08 Thread Jim Lemon
Hi Subhamitra,
I have washed the dishes and had a night's sleep, so I can now deal with
your text munging problem. First, I'll reiterate the solution I sent:

sp_8_5<-read.table("sp_8_5.tab",sep="\t",
 header=TRUE,stringsAsFactors=FALSE)
library(tseries)
library(FinTS)
# create a function that returns only the
# statistic and p.value as a string
archStatP<-function(x) {
 archout<-ArchTest(x)
 # I have truncated the values here
 return(sprintf("ChiSq = %.1f, p = %.3f",archout$statistic,archout$p.value))
}
# using "lapply", run the test on each column
spout<-lapply(sp_8_5[,2:13],archStatP)

If you look at "spout" you will see that it is a list of 12 character
strings. I arranged this as you seem to want the contents of a 3x4 table in
a document. This is one way to do it, there are others.

First, create a text table of the desired dimensions. I'll do it with loops
as you seem to be familiar with them:

# open a text file
sink("sp_8_5.txt")
for(row in 0:2) {
 for(column in 1:4)
  cat(spout[[column+row*4]],ifelse(column < 4,"\t","\n"))
}
sink()

If you open this file in a text editor (e.g. Notepad) you will see that it
contains 3 lines (rows), each with four TAB separated strings. Now to
import this into a word processing document. I don't have MS Word, so I'll
do it with Libre Office Writer and hope that the procedure is similar.

Move to where you want the table in your document
Select Insert|Text from file from the top menu
Select (highlight) the text you have imported
Select Convert|Text to table from the top menu

The highlighted area should become a table. I had to reduce the font size
from 12 to 10 to get the strings to fit into the cells.

There are probably a few more changes that you will want, so let me know if
you strike trouble.

Jim


On Fri, May 8, 2020 at 11:28 PM Subhamitra Patra 
wrote:

> Dear Sir,
>
> Thank you very much for your wonderful suggestion for my problem. Your
> suggested code has excellently worked and successfully extracted the
> statistics and p-value in another R object.
>
> Concerning your last suggestion, I attempted to separate the strings with
> TAB character in the "spout" object by using different alternative packages
> like dplyr, tidyr, qdap, ans also by using split,strsplit function so that
> can export the statistics and p-values for each column to excel, and later
> to the MSword file, but got the below error.
>
> By using the  split function, I wrote the code as,
> *string[] split = s.Split(spout, '\t')*
> where I got the following errors.
> Error: unexpected symbol in "string[] split"
> Error: unexpected symbol in "string[[]]split"
> Error in strsplit(row, "\t") : non-character argument
>
> Then I tried with  strsplit function by the below code
> *strsplit(spout, split)*
> But, got the below error as
> Error in as.character(split) :
>   cannot coerce type 'closure' to vector of type 'character'.
>
> Then used dplyr and tidyr package and the wrote the below code
> library(dplyr)
> library(tidyr)
> *separate(spout,value,into=c(“ChiSq”,”p”),sep=”,”)*
> *separate(spout,List of length 12,into=c(“ChiSq”,”p”),sep="\t")*
> But, got the errors as,
> Error: unexpected input in "separate(spout,value,into=c(“"
> Error: unexpected symbol in "separate(spout,List of"
>
> Then used qdap package with the code below
>
> *colsplit2df(spout,, c("ChiSq", "p"), ",")*
> *colsplit2df(spout,, c("ChiSq", "p"), sep = "\t")*
> But got the following errors
> Error in dataframe[, splitcol] : incorrect number of dimensions
> In addition: Warning message:
> In colsplit2df_helper(dataframe = dataframe, splitcol = splitcols[i],  :
>   dataframe object is not of the class data.frame
> Error in dataframe[, splitcol] : incorrect number of dimensions
> In addition: Warning message:
> In colsplit2df_helper(dataframe = dataframe, splitcol = splitcols[i],  :
>   dataframe object is not of the class data.frame
>
> Sir, please suggest me where I am going wrong in the above to separate
> string in the "spout" object.
>
> Thank you very much for your help.
>
> [image: Mailtrack]
> 
>  Sender
> notified by
> Mailtrack
> 
>  05/08/20,
> 06:51:46 PM
>
> On Fri, May 8, 2020 at 4:47 PM Jim Lemon  wrote:
>
>> 1) In general, *apply functions return a list with the number of elements
>> equal to the number of columns or other elements of the input data. You can
>> assign that list as I have to "spout" in the first example.
>>
>> 2) spout<-list() assigns the name "spout" to an empty list. As we are
>> processing columns 2 to 12 of the input data, spout[[i-1]] assigns the
>> results to elements 1 to 11 of the list "spout". Just a low trick.
>>
>> 1a) Yes, you can create a "wrapper" function that will return only the
>> statistic and p.value.
>>
>> # create a function that returns only the
>> # statistic and p.value as a string
>> 

Re: [R] [R ] Writing loop to estimate ARCH test for a multiple columns of a data frame?

2020-05-08 Thread Subhamitra Patra
Dear Sir,

Thank you very much for your wonderful suggestion for my problem. Your
suggested code has excellently worked and successfully extracted the
statistics and p-value in another R object.

Concerning your last suggestion, I attempted to separate the strings with
TAB character in the "spout" object by using different alternative packages
like dplyr, tidyr, qdap, ans also by using split,strsplit function so that
can export the statistics and p-values for each column to excel, and later
to the MSword file, but got the below error.

By using the  split function, I wrote the code as,
*string[] split = s.Split(spout, '\t')*
where I got the following errors.
Error: unexpected symbol in "string[] split"
Error: unexpected symbol in "string[[]]split"
Error in strsplit(row, "\t") : non-character argument

Then I tried with  strsplit function by the below code
*strsplit(spout, split)*
But, got the below error as
Error in as.character(split) :
  cannot coerce type 'closure' to vector of type 'character'.

Then used dplyr and tidyr package and the wrote the below code
library(dplyr)
library(tidyr)
*separate(spout,value,into=c(“ChiSq”,”p”),sep=”,”)*
*separate(spout,List of length 12,into=c(“ChiSq”,”p”),sep="\t")*
But, got the errors as,
Error: unexpected input in "separate(spout,value,into=c(“"
Error: unexpected symbol in "separate(spout,List of"

Then used qdap package with the code below

*colsplit2df(spout,, c("ChiSq", "p"), ",")*
*colsplit2df(spout,, c("ChiSq", "p"), sep = "\t")*
But got the following errors
Error in dataframe[, splitcol] : incorrect number of dimensions
In addition: Warning message:
In colsplit2df_helper(dataframe = dataframe, splitcol = splitcols[i],  :
  dataframe object is not of the class data.frame
Error in dataframe[, splitcol] : incorrect number of dimensions
In addition: Warning message:
In colsplit2df_helper(dataframe = dataframe, splitcol = splitcols[i],  :
  dataframe object is not of the class data.frame

Sir, please suggest me where I am going wrong in the above to separate
string in the "spout" object.

Thank you very much for your help.

[image: Mailtrack]

Sender
notified by
Mailtrack

05/08/20,
06:51:46 PM

On Fri, May 8, 2020 at 4:47 PM Jim Lemon  wrote:

> 1) In general, *apply functions return a list with the number of elements
> equal to the number of columns or other elements of the input data. You can
> assign that list as I have to "spout" in the first example.
>
> 2) spout<-list() assigns the name "spout" to an empty list. As we are
> processing columns 2 to 12 of the input data, spout[[i-1]] assigns the
> results to elements 1 to 11 of the list "spout". Just a low trick.
>
> 1a) Yes, you can create a "wrapper" function that will return only the
> statistic and p.value.
>
> # create a function that returns only the
> # statistic and p.value as a string
> archStatP<-function(x) {
>  archout<-ArchTest(x)
>  return(sprintf("ChiSq = %f, p = %f",archout$statistic,archout$p.value))
> }
> # using "lapply", run the test on each column
> spout<-lapply(sp_8_5[,2:12],archStatP)
>
> Note that I should have used "lapply". I didn't check the output carefully
> enough.
>
> 2a) Now you only have to separate the strings in "spout" with TAB
> characters and import the result into Excel. I have to wash the dishes, so
> you're on your own.
>
> Jim
>
> On Fri, May 8, 2020 at 8:26 PM Subhamitra Patra <
> subhamitra.pa...@gmail.com> wrote:
>
>> Dear Sir,
>>
>> Thank you very much for such an excellent solution to my problem. I was
>> trying sapply function since last days, but was really unable to write
>> properly. Now, I understood my mistake in using sapply function in the
>> code. Therefore, I have two queries regarding this which I want to discuss
>> here just for my learning purpose.
>>
>> 1. While using sapply function for estimating one method across the
>> columns of a data frame, one needs to define the list of the output table
>> after using sapply so that the test results for each column will be
>> consistently stored in an output object, right?
>>
>> 2. In the spout<- list() command, what spout[[i-1]]  indicates?
>>
>> Sir, one more possibility which I would like to ask related to my above
>> problem just to learn for further R programming language.
>>
>> After running your suggested code, all the results for each column are
>> being stored in the spout object. From this, I need only the statistics and
>> P-value for each column. So, my queries are:
>>
>> 1. Is there any way to extract only two values (i.e., statistics and
>> p-value) for each column that stored in spout object and save these two
>> values in another R data frame for each column?
>>  or
>> 2. Is there any possibility that the statistics and p-value
>> calculated for each column can directly export to a word file in a table
>> format (having 4 

Re: [R] [R ] Writing loop to estimate ARCH test for a multiple columns of a data frame?

2020-05-08 Thread Jim Lemon
1) In general, *apply functions return a list with the number of elements
equal to the number of columns or other elements of the input data. You can
assign that list as I have to "spout" in the first example.

2) spout<-list() assigns the name "spout" to an empty list. As we are
processing columns 2 to 12 of the input data, spout[[i-1]] assigns the
results to elements 1 to 11 of the list "spout". Just a low trick.

1a) Yes, you can create a "wrapper" function that will return only the
statistic and p.value.

# create a function that returns only the
# statistic and p.value as a string
archStatP<-function(x) {
 archout<-ArchTest(x)
 return(sprintf("ChiSq = %f, p = %f",archout$statistic,archout$p.value))
}
# using "lapply", run the test on each column
spout<-lapply(sp_8_5[,2:12],archStatP)

Note that I should have used "lapply". I didn't check the output carefully
enough.

2a) Now you only have to separate the strings in "spout" with TAB
characters and import the result into Excel. I have to wash the dishes, so
you're on your own.

Jim

On Fri, May 8, 2020 at 8:26 PM Subhamitra Patra 
wrote:

> Dear Sir,
>
> Thank you very much for such an excellent solution to my problem. I was
> trying sapply function since last days, but was really unable to write
> properly. Now, I understood my mistake in using sapply function in the
> code. Therefore, I have two queries regarding this which I want to discuss
> here just for my learning purpose.
>
> 1. While using sapply function for estimating one method across the
> columns of a data frame, one needs to define the list of the output table
> after using sapply so that the test results for each column will be
> consistently stored in an output object, right?
>
> 2. In the spout<- list() command, what spout[[i-1]]  indicates?
>
> Sir, one more possibility which I would like to ask related to my above
> problem just to learn for further R programming language.
>
> After running your suggested code, all the results for each column are
> being stored in the spout object. From this, I need only the statistics and
> P-value for each column. So, my queries are:
>
> 1. Is there any way to extract only two values (i.e., statistics and
> p-value) for each column that stored in spout object and save these two
> values in another R data frame for each column?
>  or
> 2. Is there any possibility that the statistics and p-value calculated for
> each column can directly export to a word file in a table format (having 4
> columns and 3 rows). In particular, is it possible to extract both
> statistic and p-value results for each column to an MS word file with the
> format of A1, A2, A3, A4 column results in 1st row, A5, A6, A7, A8 column
> results in 2nd row, and A9, A10, A11, A12 column results in the 3rd row of
> the table?
>
>
> Like before, your suggestion will definitely help me to learn the advanced
> R language.
>
> Thank you very much for your help.
>
> [image: Mailtrack]
> 
>  Sender
> notified by
> Mailtrack
> 
>  05/08/20,
> 03:47:26 PM
>
> On Fri, May 8, 2020 at 2:37 PM Jim Lemon  wrote:
>
>> Hi Subhamitra,
>> This isn't too hard:
>>
>> # read in the sample data that was
>> # saved in the file "sp_8_5.tab"
>> sp_8_5<-read.table("sp_8_5.tab",sep="\t",
>>  header=TRUE,stringsAsFactors=FALSE)
>> library(tseries)
>> library(FinTS)
>> # using "sapply", run the test on each column
>> spout<-sapply(sp_8_5[,2:12],ArchTest)
>>
>> The list "spout" contains the test results. If you really want to use a
>> loop:
>>
>> spout<-list()
>> for(i in 2:12) spout[[i-1]]<-ArchTest(sp_8_5[,i])
>>
>> Jim
>>
>>
>> On Fri, May 8, 2020 at 5:27 PM Subhamitra Patra <
>> subhamitra.pa...@gmail.com> wrote:
>>
>>> Dear Sir,
>>>
>>> Herewith I am pasting a part of my sample data having 12 columns below,
>>> and want to calculate ARCH test for the 12 columns by using a loop.
>>>
>>>
>
> --
> *Best Regards,*
> *Subhamitra Patra*
> *Phd. Research Scholar*
> *Department of Humanities and Social Sciences*
> *Indian Institute of Technology, Kharagpur*
> *INDIA*
>

[[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] [R ] Writing loop to estimate ARCH test for a multiple columns of a data frame?

2020-05-08 Thread Subhamitra Patra
Dear Sir,

Thank you very much for such an excellent solution to my problem. I was
trying sapply function since last days, but was really unable to write
properly. Now, I understood my mistake in using sapply function in the
code. Therefore, I have two queries regarding this which I want to discuss
here just for my learning purpose.

1. While using sapply function for estimating one method across the columns
of a data frame, one needs to define the list of the output table after
using sapply so that the test results for each column will be consistently
stored in an output object, right?

2. In the spout<- list() command, what spout[[i-1]]  indicates?

Sir, one more possibility which I would like to ask related to my above
problem just to learn for further R programming language.

After running your suggested code, all the results for each column are
being stored in the spout object. From this, I need only the statistics and
P-value for each column. So, my queries are:

1. Is there any way to extract only two values (i.e., statistics and
p-value) for each column that stored in spout object and save these two
values in another R data frame for each column?
 or
2. Is there any possibility that the statistics and p-value calculated for
each column can directly export to a word file in a table format (having 4
columns and 3 rows). In particular, is it possible to extract both
statistic and p-value results for each column to an MS word file with the
format of A1, A2, A3, A4 column results in 1st row, A5, A6, A7, A8 column
results in 2nd row, and A9, A10, A11, A12 column results in the 3rd row of
the table?


Like before, your suggestion will definitely help me to learn the advanced
R language.

Thank you very much for your help.

[image: Mailtrack]

Sender
notified by
Mailtrack

05/08/20,
03:47:26 PM

On Fri, May 8, 2020 at 2:37 PM Jim Lemon  wrote:

> Hi Subhamitra,
> This isn't too hard:
>
> # read in the sample data that was
> # saved in the file "sp_8_5.tab"
> sp_8_5<-read.table("sp_8_5.tab",sep="\t",
>  header=TRUE,stringsAsFactors=FALSE)
> library(tseries)
> library(FinTS)
> # using "sapply", run the test on each column
> spout<-sapply(sp_8_5[,2:12],ArchTest)
>
> The list "spout" contains the test results. If you really want to use a
> loop:
>
> spout<-list()
> for(i in 2:12) spout[[i-1]]<-ArchTest(sp_8_5[,i])
>
> Jim
>
>
> On Fri, May 8, 2020 at 5:27 PM Subhamitra Patra <
> subhamitra.pa...@gmail.com> wrote:
>
>> Dear Sir,
>>
>> Herewith I am pasting a part of my sample data having 12 columns below,
>> and want to calculate ARCH test for the 12 columns by using a loop.
>>
>>

-- 
*Best Regards,*
*Subhamitra Patra*
*Phd. Research Scholar*
*Department of Humanities and Social Sciences*
*Indian Institute of Technology, Kharagpur*
*INDIA*

[[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] [R ] Writing loop to estimate ARCH test for a multiple columns of a data frame?

2020-05-08 Thread Jim Lemon
Hi Subhamitra,
This isn't too hard:

# read in the sample data that was
# saved in the file "sp_8_5.tab"
sp_8_5<-read.table("sp_8_5.tab",sep="\t",
 header=TRUE,stringsAsFactors=FALSE)
library(tseries)
library(FinTS)
# using "sapply", run the test on each column
spout<-sapply(sp_8_5[,2:12],ArchTest)

The list "spout" contains the test results. If you really want to use a
loop:

spout<-list()
for(i in 2:12) spout[[i-1]]<-ArchTest(sp_8_5[,i])

Jim


On Fri, May 8, 2020 at 5:27 PM Subhamitra Patra 
wrote:

> Dear Sir,
>
> Herewith I am pasting a part of my sample data having 12 columns below,
> and want to calculate ARCH test for the 12 columns by using a loop.
>
>

[[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] [R ] Writing loop to estimate ARCH test for a multiple columns of a data frame?

2020-05-08 Thread Subhamitra Patra
Dear Sir,

Herewith I am pasting a part of my sample data having 12 columns below, and
want to calculate ARCH test for the 12 columns by using a loop.

Please help me in this regard. Thank you very much for your help.

Year_Month A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12
94-Jan 0.051197 7.05E-05 0.058806 -0.00818 0.538001 0.009766 0.025787
0.035478 0.056663 0.014665 0.23132 0.008644
94-Feb 0.06424 -0.01086 0.049823 -0.04989 0.557945 0.00974 0.027757 0.021494
0.016947 0.014584 0.229776 -0.02317
94-Mar 0.056168 -0.00626 0.061555 -0.03427 0.524705 0.009694 0.027632
-0.00656 0.008358 0.014499 0.190421 0.003026
94-Apr 0.129051 0.043813 0.060453 0.017469 0.545895 0.009615 0.01932 0.01171
0.016003 0.014412 0.140396 0.017556
94-May 0.142182 -0.03848 0.059938 0.015054 0.525178 0.009479 0.027741
0.000605 0.0185 0.014327 0.093228 -0.03989
94-Jun 0.152981 -0.03227 0.071485 -0.01025 0.363882 0.009323 0.030762
0.013005 0.03634 0.014239 0.035625 -0.01355
94-Jul 0.16216 0.046374 0.073669 0.020508 0.3405 0.00926 0.044822 -0.00954
0.042422 0.014154 0.037954 0.00097
94-Aug 0.124355 -0.06952 0.091429 0.015932 0.38519 0.009269 0.071701
0.000623 0.051954 0.01407 0.055852 0.007522
94-Sep 0.059405 0.057487 0.086265 -0.01169 0.401963 0.009171 0.086685
-0.01058 0.054404 0.013986 0.07285 0.002022
94-Oct 0.0594 0.021166 0.080765 0.006442 0.438915 0.009041 0.070351 0.006776
0.033622 0.013906 0.068344 -0.01532
94-Nov 0.072064 -0.03104 0.079567 -0.03295 0.521214 0.008986 0.066044
-0.01853 0.035202 0.013826 0.067093 -0.02278
94-Dec 0.068208 0.01024 0.069919 -0.01507 0.461059 0.008856 0.050985
0.009514 0.008638 0.013744 0.040348 0.00423
95-Jan 0.079074 -0.00153 0.070458 -0.04205 0.506227 0.00883 0.046561
-0.03907 0.015322 0.013662 0.034103 -0.00888
95-Feb 0.074231 -0.05728 0.062612 0.035992 0.487126 0.008815 0.052816
-0.01344 0.06728 0.013583 0.063281 -0.0054
95-Mar 0.065212 0.056084 0.095783 0.006825 0.476386 0.008774 0.047498
0.015178 0.040273 0.013499 0.060805 0.006099
95-Apr 0.081238 0.024283 0.098827 0.005791 0.432363 0.008748 0.06047
0.011613 0.013068 0.013417 0.058321 -0.01281
95-May 0.093726 0.008623 0.076698 0.027274 0.321103 0.008679 0.037962
0.00115 0.013647 0.013339 0.066724 -0.00271
95-Jun 0.113998 0.005484 0.073392 -0.00252 0.38195 0.008684 0.042794
-0.01133 0.054244 0.013261 0.055655 0.015941
95-Jul 0.097076 0.008842 0.090776 0.006378 0.622055 0.008728 0.036476
0.016159 0.055301 0.013188 0.057034 -0.0036
95-Aug 0.075751 0.002437 0.094687 -0.00398 0.637972 0.008839 0.052791
-0.00819 0.327487 0.013114 0.067734 0.00565
95-Sep 0.074714 0.001279 0.091216 0.013169 0.656225 0.008956 0.086582
-0.0013 0.690172 0.01304 0.059523 0.028675
95-Oct 0.048771 -0.01775 0.098525 0.003447 0.68386 0.009071 0.091073
-0.01597 0.640065 0.012967 0.030469 0.005139
95-Nov 0.069776 -0.00164 0.077763 0.00158 0.559675 0.008808 0.094129 0.01832
0.726821 0.012893 0.030908 -0.00955
95-Dec 0.135469 0.001886 0.074658 0.01263 0.563716 0.00 0.113828
0.011372 0.737532 0.012822 0.224459 -0.00186
96-Jan 0.175166 0.00068 0.071721 0.030701 0.534648 0.009114 0.086481
0.016228 0.687297 0.013112 0.349764 0.000727
96-Feb 0.167327 0.013771 0.055352 -0.03142 0.556339 0.009119 0.080475
-0.00691 0.696365 0.013077 0.342758 -4.90E-05
96-Mar 0.158759 -0.02094 0.042232 -0.00331 0.532126 0.009041 0.077231
0.009009 0.579396 0.012271 0.342196 -0.002
96-Apr 0.116956 0.02624 0.051037 -0.01496 0.575416 0.009123 0.079496
0.017197 0.557262 0.012094 0.299566 0.022657
96-May 0.109049 -0.02648 0.059972 0.00658 0.616302 0.009086 0.095365
-0.01682 0.521757 0.011933 0.074309 0.021621
96-Jun 0.102001 2.71E-05 0.060901 -0.00372 0.593491 0.009213 0.095232
0.001363 0.523983 0.011757 0.070504 -0.00507
96-Jul 0.079941 -0.02107 0.046018 -0.00708 0.562537 0.009136 0.094451
-0.01132 0.534417 0.011413 0.073706 -0.00615
96-Aug 0.109775 0.005178 0.051713 0.007174 0.54939 0.009008 0.088945
-0.01136 0.445843 0.010925 0.066559 0.009937
96-Sep 0.089581 -0.0005 0.049835 0.016873 0.54664 0.008887 0.082659 0.011384
0.435423 0.010697 0.091269 0.00687
96-Oct 0.07429 -0.01499 0.063584 0.008829 0.485504 0.008965 0.072986
-0.01695 0.54066 0.010649 0.325364 0.012261
96-Nov 0.060441 0.021057 0.100844 0.018152 0.415023 0.009033 0.072366
-0.00222 0.646444 0.010653 0.323194 0.01409
96-Dec 0.061482 0.0218 0.142038 -6.42E-06 0.492536 0.008947 0.081333
-0.02433 0.661019 0.010555 0.367988 -0.00023
97-Jan 0.053437 0.025314 0.137257 -0.00659 0.578904 0.008841 0.074613
-0.0068 0.628154 0.010609 0.355763 0.00581
97-Feb 0.080489 -0.01411 0.123644 0.009692 0.571364 0.008794 0.07673
0.005832 0.549697 0.010781 0.21588 0.070824
97-Mar 0.097621 0.00073 0.115192 -0.04503 0.639719 0.008686 0.065906
-0.01063 0.543819 0.010442 0.129773 0.004692
97-Apr 0.112502 -0.00052 0.064499 0.007382 0.648139 0.008674 0.038621
0.006408 0.591661 0.010283 0.079461 0.009395
97-May 0.109789 0.028968 0.079382 0.032543 0.530901 0.008884 0.029301
0.039566 0.492504 0.01004 0.042617 -0.00151
97-Jun 0.087521 -0.03031 0.037389 0.001738 0.500643 0.00886 

Re: [R] [R ] Writing loop to estimate ARCH test for a multiple columns of a data frame?

2020-05-07 Thread Jim Lemon
Hi Subhamitra,
For some reason, your data didn't make it through. Maybe you tried to
send an .xls or .xlsx file. If so, export it as CSV or if it's not too
big, just paste the text into your email.

Jim

On Thu, May 7, 2020 at 10:30 PM Subhamitra Patra
 wrote:
>
> Dear R-users,
>
> I want to estimate ARCH test for multiple columns (i.e.,  from 2:21 COLUMNS
> ) in my data. For this purpose, I want to run a loop to calculate ARCH test
> results for each column in the data frame. I tried by using for loop and
> lapply function, but unable to write a loop for computing the ARCH test
> simultaneously for each column (i.e., from 2:21 columns) of my data frame.
>
> Below is my ARCH test code which I want to estimate for multiple columns of
> the data frame in a loop.
>
> library(tseries)
>
> library(FinTS)
>
> ArchTest (A, lags=1, demean = FALSE)
>
> Hence, A is a vector for which the ARCH test result is calculated. Here, I
> want to write a loop so that the ArchTest can be calculated simultaneously
> for each column of my data frame. From ARCH test result, I require only the
> calculated Chi-square value and its p-value for each column that stored in
> another matrix or object for each column as an output file.
>
> For your convenience, I attached my sample data below. Please find it.
>
> Please help me for which I shall be always grateful to you.
>
> Thank you.
>
> --
> *Best Regards,*
> *Subhamitra Patra*
> *Phd. Research Scholar*
> *Department of Humanities and Social Sciences*
> *Indian Institute of Technology, Kharagpur*
> *INDIA*
>
> [image: Mailtrack]
> 
> Sender
> notified by
> Mailtrack
> 
> 05/07/20,
> 05:51:03 PM
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] [R ] Writing loop to estimate ARCH test for a multiple columns of a data frame?

2020-05-07 Thread Subhamitra Patra
Dear R-users,

I want to estimate ARCH test for multiple columns (i.e.,  from 2:21 COLUMNS
) in my data. For this purpose, I want to run a loop to calculate ARCH test
results for each column in the data frame. I tried by using for loop and
lapply function, but unable to write a loop for computing the ARCH test
simultaneously for each column (i.e., from 2:21 columns) of my data frame.

Below is my ARCH test code which I want to estimate for multiple columns of
the data frame in a loop.

library(tseries)

library(FinTS)

ArchTest (A, lags=1, demean = FALSE)

Hence, A is a vector for which the ARCH test result is calculated. Here, I
want to write a loop so that the ArchTest can be calculated simultaneously
for each column of my data frame. From ARCH test result, I require only the
calculated Chi-square value and its p-value for each column that stored in
another matrix or object for each column as an output file.

For your convenience, I attached my sample data below. Please find it.

Please help me for which I shall be always grateful to you.

Thank you.

-- 
*Best Regards,*
*Subhamitra Patra*
*Phd. Research Scholar*
*Department of Humanities and Social Sciences*
*Indian Institute of Technology, Kharagpur*
*INDIA*

[image: Mailtrack]

Sender
notified by
Mailtrack

05/07/20,
05:51:03 PM
__
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] If Loop I Think

2019-10-27 Thread William Michels via R-help
Hi Phillip,

I wanted to follow up with you regarding your earlier post. Below is a
different way to work up your data than I posted earlier.

I took the baseball data you posted, stripped out
leading-and-following blank lines, removed all trailing spaces on each
line, and removed the "R1", "R2" and "R3" column names, since they're
blank columns anyway. I then read this text file ("diamond2.txt") into
R using the read.table() call below. Note the use of the sep=" "
parameter--it is very important to include this parameter when
analyzing your dataset in R, as it is not the default setting. I was
then able to generate the "R1", "R2", "R3" columns you sought, using
apply() with anonymous functions:

> testAD <- read.table("diamond2.txt", header=T, sep=" ", na.strings="", 
> fill=T, row.names=NULL, stringsAsFactors=F)
> testAD$R1=rep(NA, 14)
> testAD$R2=rep(NA, 14)
> testAD$R3=rep(NA, 14)
> testAD[ ,c(6:8)] <- apply(testAD[ ,c(3:5)], 2, FUN=function(x) 
> {ifelse(test=nchar(x), yes=1, no=0)} )
> testAD[ ,c(6:8)] <- apply(testAD[ ,c(6:8)], 2, FUN=function(x) 
> {ifelse(test=!is.na(x), yes=x, no=0)} )
> testAD
   Row Outs RunnerFirst RunnerSecond RunnerThird R1 R2 R3
110   0  0  0
221   0  0  0
331   0  0  0
441arenn001   1  0  0
552arenn001   1  0  0
660   0  0  0
770perad001   1  0  0
880polla001 perad001  1  1  0
990goldp001 polla001perad001  1  1  1
10  100 lambj001goldp001  0  1  1
11  111 lambj001goldp001  0  1  1
12  122 lambj001  0  0  1
13  130   0  0  0
14  141   0  0  0
>

HTH,

Bill.

W. Michels, Ph.D.


On Thu, Oct 24, 2019 at 12:44 PM William Michels  wrote:
>
> Hi Phillip,

__
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] If Loop I Think

2019-10-24 Thread William Michels via R-help
"" "lambj001" "goldp001"
[11,] "1"  "" "lambj001" "goldp001"
[12,] "2"  "" "" "lambj001"
[13,] "0"  NA NA NA
[14,] "1"  NA NA NA
> cc
  [,1] [,2] [,3]
 [1,]   NA   NA   NA
 [2,]   NA   NA   NA
 [3,]   NA   NA   NA
 [4,]1   NA   NA
 [5,]1   NA   NA
 [6,]   NA   NA   NA
 [7,]1   NA   NA
 [8,]11   NA
 [9,]111
[10,]011
[11,]011
[12,]001
[13,]   NA   NA   NA
[14,]   NA   NA   NA
>

HTH, Bill.

W. Michels, Ph.D.





On Wed, Oct 23, 2019 at 12:40 AM PIKAL Petr  wrote:
>
> Hi
>
> ***do not think in if or if loops in R***.
>
> to elaborate Jim's solution further
>
> With simple function based on logical expression
> fff <- function(x) (x!="")+0
>
> you could use apply
>
> t(apply(phdf[,3:5], 1, fff))
>
> and add results to your data frame columns
> phdf[, 6:8] <- t(apply(phdf[,3:5], 1, fff))
>
> Regarding some tutorial
>
> Basic stuff is in R-intro, there is excellent documentation to each function.
>
> And as R users pool is huge, you could simply ask Google
> e.g.
> r change values based on condition
>
> Cheers
> Petr
>
> > -Original Message-
> > From: R-help  On Behalf Of Jim Lemon
> > Sent: Wednesday, October 23, 2019 12:26 AM
> > To: Phillip Heinrich 
> > Cc: r-help 
> > Subject: Re: [R] If Loop I Think
> >
> > Hi Philip,
> > Try this:
> >
> > phdf<-read.table(
> > text="Row Outs RunnerFirst RunnerSecond RunnerThird R1 R2 R3
> > 1 0
> > 2 1
> > 3 1
> > 4 1 arenn001
> > 5 2 arenn001
> > 6 0
> > 7 0 perad001
> > 8 0 polla001 perad001
> > 9 0 goldp001 polla001 perad001
> > 10 0  lambj001 goldp001
> > 11 1  lambj001 goldp001
> > 12 2   lambj001
> > 13 0
> > 14 1   ",
> > header=TRUE,stringsAsFactors=FALSE,fill=TRUE)
> > phdf$R1<-ifelse(nchar(phdf$RunnerFirst) > 0,1,0)
> > phdf$R2<-ifelse(nchar(phdf$RunnerSecond) > 0,1,0)
> > phdf$R3<-ifelse(nchar(phdf$RunnerThird) > 0,1,0)
> >
> > Jim
> >
> > On Wed, Oct 23, 2019 at 7:54 AM Phillip Heinrich 
> > wrote:
> > >
> > >   Row Outs RunnerFirst RunnerSecond RunnerThird R1 R2 R3
> > >   1 0
> > >   2 1
> > >   3 1
> > >   4 1 arenn001
> > >   5 2 arenn001
> > >   6 0
> > >   7 0 perad001
> > >   8 0 polla001 perad001
> > >   9 0 goldp001 polla001 perad001
> > >   10 0  lambj001 goldp001
> > >   11 1  lambj001 goldp001
> > >   12 2   lambj001
> > >   13 0
> > >   14 1
> > >
> > >
> > >
> > > With the above data, Arizona Diamondbacks baseball, I’m trying to put
> > zeros into the R1 column is the RunnerFirst column is blank and a one if the
> > column has a coded entry such as rows 4,5,7,8,& 9.  Similarly I want zeros 
> > in
> > R2 and R3 if RunnerSecond and RunnerThird respectively are blank and ones
> > if there is an entry.
> > >
> > > I’ve tried everything I know how to do such as “If Loops”, “If-Then 
> > > loops”,
> > “apply”, “sapply”, etc.  I wrote function below and it ran without errors 
> > but I
> > have no idea what to do with it to accomplish my goal:
> > >
> > > R1 <- function(x) {
> > >   if (ari18.test3$RunnerFirst == " "){
> > >ari18.test3$R1 <- 0
> > >return(R1)
> > >  }else{
> > >R1 <- ari18.test3$R1 <- 1
> > >return(R1)
> > >  }
> > >}
> > >
> > > The name of the data frame is ari18.test3
> > >
> > > On a more philosophical note, data handling in R seems to be made up of
> > thousands of details with no over-riding principles.  I’ve read two books 
> > on R
> > and a number of tutorial and watched several videos but I don’t seem to be
> > making any progress.  Can anyone suggest videos, or tutorials, or books that
> > might help?  Database stuff has never been my strong point but I’m
> > determined to learn.
> > >
> > > Thanks,
> > > Philip Heinrich
> > > [[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.
> __
> 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] If Loop I Think

2019-10-23 Thread PIKAL Petr
Hi

***do not think in if or if loops in R***.

to elaborate Jim's solution further

With simple function based on logical expression
fff <- function(x) (x!="")+0

you could use apply

t(apply(phdf[,3:5], 1, fff))

and add results to your data frame columns
phdf[, 6:8] <- t(apply(phdf[,3:5], 1, fff))

Regarding some tutorial

Basic stuff is in R-intro, there is excellent documentation to each function.

And as R users pool is huge, you could simply ask Google
e.g.
r change values based on condition

Cheers
Petr

> -Original Message-
> From: R-help  On Behalf Of Jim Lemon
> Sent: Wednesday, October 23, 2019 12:26 AM
> To: Phillip Heinrich 
> Cc: r-help 
> Subject: Re: [R] If Loop I Think
> 
> Hi Philip,
> Try this:
> 
> phdf<-read.table(
> text="Row Outs RunnerFirst RunnerSecond RunnerThird R1 R2 R3
> 1 0
> 2 1
> 3 1
> 4 1 arenn001
> 5 2 arenn001
> 6 0
> 7 0 perad001
> 8 0 polla001 perad001
> 9 0 goldp001 polla001 perad001
> 10 0  lambj001 goldp001
> 11 1  lambj001 goldp001
> 12 2   lambj001
> 13 0
> 14 1   ",
> header=TRUE,stringsAsFactors=FALSE,fill=TRUE)
> phdf$R1<-ifelse(nchar(phdf$RunnerFirst) > 0,1,0)
> phdf$R2<-ifelse(nchar(phdf$RunnerSecond) > 0,1,0)
> phdf$R3<-ifelse(nchar(phdf$RunnerThird) > 0,1,0)
> 
> Jim
> 
> On Wed, Oct 23, 2019 at 7:54 AM Phillip Heinrich 
> wrote:
> >
> >   Row Outs RunnerFirst RunnerSecond RunnerThird R1 R2 R3
> >   1 0
> >   2 1
> >   3 1
> >   4 1 arenn001
> >   5 2 arenn001
> >   6 0
> >   7 0 perad001
> >   8 0 polla001 perad001
> >   9 0 goldp001 polla001 perad001
> >   10 0  lambj001 goldp001
> >   11 1  lambj001 goldp001
> >   12 2   lambj001
> >   13 0
> >   14 1
> >
> >
> >
> > With the above data, Arizona Diamondbacks baseball, I’m trying to put
> zeros into the R1 column is the RunnerFirst column is blank and a one if the
> column has a coded entry such as rows 4,5,7,8,& 9.  Similarly I want zeros in
> R2 and R3 if RunnerSecond and RunnerThird respectively are blank and ones
> if there is an entry.
> >
> > I’ve tried everything I know how to do such as “If Loops”, “If-Then loops”,
> “apply”, “sapply”, etc.  I wrote function below and it ran without errors but 
> I
> have no idea what to do with it to accomplish my goal:
> >
> > R1 <- function(x) {
> >   if (ari18.test3$RunnerFirst == " "){
> >ari18.test3$R1 <- 0
> >return(R1)
> >  }else{
> >R1 <- ari18.test3$R1 <- 1
> >return(R1)
> >  }
> >}
> >
> > The name of the data frame is ari18.test3
> >
> > On a more philosophical note, data handling in R seems to be made up of
> thousands of details with no over-riding principles.  I’ve read two books on R
> and a number of tutorial and watched several videos but I don’t seem to be
> making any progress.  Can anyone suggest videos, or tutorials, or books that
> might help?  Database stuff has never been my strong point but I’m
> determined to learn.
> >
> > Thanks,
> > Philip Heinrich
> > [[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.
__
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] If Loop I Think

2019-10-22 Thread Jim Lemon
Notice that I used the argument stringsAsFactors=FALSE to do this when
reading in.
What I did was to change Rn columns to 1 if there were any characters
in the corresponding Runnerxxx column and 0 otherwise. The "nchar"
function returns the number of characters in a string. If I apply ">0"
to it, I get TRUE(1) if nchar returns a number larger than zero and
FALSE (0) otherwise. By using the result of this operation as the
first argument in the call to "ifelse", I can set the values of the Rn
columns one by one. It is possible to do all three in one call with an
appropriate  function:

whos_on_first<-function(x)
 return(as.numeric(nchar(x) > 0))
phdf[,6:8]<-sapply(phdf[,3:5],whos_on_first)

Jiim

On Wed, Oct 23, 2019 at 11:20 AM Phillip Heinrich  wrote:
>
> The routine you suggested worked once I changed RunnerFirst, Second, & Third
> to character vectors.
>
> But I really don't understand what the code is doing.  I understand the
> Ifelse(no-character in RunnerFirst vector) but the 0,1,0 is a mystery.  I
> assume the first zero is if the field is blank and a one if there is
> something in the field.  But what does the third number do?  And why is a >
> symbol used as opposed to an = sign?
>
> Again the bigger question is how do I learn this stuff?  I bought another
> book, "R Projects for Dummies".  I will work through the examples over the
> next week and hope I'll know more once I'm done.
>
> Can you suggest any other sources?
>
> Thanks.
>
> -Original Message-----
> From: Jim Lemon
> Sent: Tuesday, October 22, 2019 3:26 PM
> To: Phillip Heinrich
> Cc: r-help
> Subject: Re: [R] If Loop I Think
>
> Hi Philip,
> Try this:
>
> phdf<-read.table(
> text="Row Outs RunnerFirst RunnerSecond RunnerThird R1 R2 R3
> 1 0
> 2 1
> 3 1
> 4 1 arenn001
> 5 2 arenn001
> 6 0
> 7 0 perad001
> 8 0 polla001 perad001
> 9 0 goldp001 polla001 perad001
> 10 0  lambj001 goldp001
> 11 1  lambj001 goldp001
> 12 2   lambj001
> 13 0
> 14 1   ",
> header=TRUE,stringsAsFactors=FALSE,fill=TRUE)
> phdf$R1<-ifelse(nchar(phdf$RunnerFirst) > 0,1,0)
> phdf$R2<-ifelse(nchar(phdf$RunnerSecond) > 0,1,0)
> phdf$R3<-ifelse(nchar(phdf$RunnerThird) > 0,1,0)
>
> Jim
>
> On Wed, Oct 23, 2019 at 7:54 AM Phillip Heinrich  wrote:
> >
> >   Row Outs RunnerFirst RunnerSecond RunnerThird R1 R2 R3
> >   1 0
> >   2 1
> >   3 1
> >   4 1 arenn001
> >   5 2 arenn001
> >   6 0
> >   7 0 perad001
> >   8 0 polla001 perad001
> >   9 0 goldp001 polla001 perad001
> >   10 0  lambj001 goldp001
> >   11 1  lambj001 goldp001
> >   12 2   lambj001
> >   13 0
> >   14 1
> >
> >
> >
> > With the above data, Arizona Diamondbacks baseball, I’m trying to put
> > zeros into the R1 column is the RunnerFirst column is blank and a one if
> > the column has a coded entry such as rows 4,5,7,8,& 9.  Similarly I want
> > zeros in R2 and R3 if RunnerSecond and RunnerThird respectively are blank
> > and ones if there is an entry.
> >
> > I’ve tried everything I know how to do such as “If Loops”, “If-Then loops”,
> > “apply”, “sapply”, etc.  I wrote function below and it ran without errors
> > but I have no idea what to do with it to accomplish my goal:
> >
> > R1 <- function(x) {
> >   if (ari18.test3$RunnerFirst == " "){
> >ari18.test3$R1 <- 0
> >return(R1)
> >  }else{
> >R1 <- ari18.test3$R1 <- 1
> >return(R1)
> >  }
> >}
> >
> > The name of the data frame is ari18.test3
> >
> > On a more philosophical note, data handling in R seems to be made up of
> > thousands of details with no over-riding principles.  I’ve read two books
> > on R and a number of tutorial and watched several videos but I don’t seem
> > to be making any progress.  Can anyone suggest videos, or tutorials, or
> > books that might help?  Database stuff has never been my strong point but
> > I’m determined to learn.
> >
> > Thanks,
> > Philip Heinrich
> > [[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] If Loop I Think

2019-10-22 Thread David Winsemius



On 10/22/19 1:54 PM, Phillip Heinrich wrote:

   Row Outs RunnerFirst RunnerSecond RunnerThird R1 R2 R3
   1 0
   2 1
   3 1
   4 1 arenn001
   5 2 arenn001
   6 0
   7 0 perad001
   8 0 polla001 perad001
   9 0 goldp001 polla001 perad001
   10 0  lambj001 goldp001
   11 1  lambj001 goldp001
   12 2   lambj001
   13 0
   14 1



With the above data, Arizona Diamondbacks baseball, I’m trying to put zeros into 
the R1 column is the RunnerFirst column is blank and a one if the column has a 
coded entry such as rows 4,5,7,8,& 9.  Similarly I want zeros in R2 and R3 if 
RunnerSecond and RunnerThird respectively are blank and ones if there is an entry.

I’ve tried everything I know how to do such as “If Loops”, “If-Then loops”, 
“apply”, “sapply”, etc.  I wrote function below and it ran without errors but I 
have no idea what to do with it to accomplish my goal:

R1 <- function(x) {
   if (ari18.test3$RunnerFirst == " "){
ari18.test3$R1 <- 0
return(R1)
  }else{
R1 <- ari18.test3$R1 <- 1
return(R1)
  }
}

The name of the data frame is ari18.test3

On a more philosophical note, data handling in R seems to be made up of 
thousands of details with no over-riding principles.  I’ve read two books on R 
and a number of tutorial and watched several videos but I don’t seem to be 
making any progress.  Can anyone suggest videos, or tutorials, or books that 
might help?  Database stuff has never been my strong point but I’m determined 
to learn.

Thanks,
Philip Heinrich
[[alternative HTML version deleted]]


I'm not sure how well you read instructions since you submitted this in 
HTML. The advice I would give for learning data handling is to study R's 
data structures and the help pages for `[<-`, `lapply`,`merge`, and the 
concept of vectorization. If you don't know Boolean logic well, then 
studying that topic would also be helpful. Studying the help page for 
`[<-` is a stepo may newbies think they can avoid, but mastery will 
elude you until you have read through it probably ten or tweny times.


Here's how to input that data and create R1. The methods to create 
R2,and R3 would take two more similar lines of code.


> dat <- read.table(text="  Row Outs RunnerFirst RunnerSecond 
RunnerThird R1 R2 R3

+   1 0
+   2 1
+   3 1
+   4 1 arenn001
+   5 2 arenn001
+   6 0
+   7 0 perad001
+   8 0 polla001 perad001
+   9 0 goldp001 polla001 perad001
+   10 0  lambj001 goldp001
+   11 1  lambj001 goldp001
+   12 2   lambj001
+   13 0
+   14 1   ", header=TRUE, fill=TRUE)
> dat
   Row Outs RunnerFirst RunnerSecond RunnerThird R1 R2 R3
1    1    0  NA NA NA
2    2    1  NA NA NA
3    3    1  NA NA NA
4    4    1    arenn001  NA NA NA
5    5    2    arenn001  NA NA NA
6    6    0  NA NA NA
7    7    0    perad001  NA NA NA
8    8    0    polla001 perad001 NA NA NA
9    9    0    goldp001 polla001    perad001 NA NA NA
10  10    0    lambj001 goldp001 NA NA NA
11  11    1    lambj001 goldp001 NA NA NA
12  12    2    lambj001  NA NA NA
13  13    0  NA NA NA
14  14    1  NA NA NA
> levels(dat$RunnerFirst)
[1] "" "arenn001" "goldp001" "lambj001" "perad001" "polla001"
> dat$R1 <- as.numeric( dat$RunnerFirst != "")
> dat$R1
 [1] 0 0 0 1 1 0 1 1 1 1 1 1 0 0

--

David.




__
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] If Loop I Think

2019-10-22 Thread Jim Lemon
Hi Philip,
Try this:

phdf<-read.table(
text="Row Outs RunnerFirst RunnerSecond RunnerThird R1 R2 R3
1 0
2 1
3 1
4 1 arenn001
5 2 arenn001
6 0
7 0 perad001
8 0 polla001 perad001
9 0 goldp001 polla001 perad001
10 0  lambj001 goldp001
11 1  lambj001 goldp001
12 2   lambj001
13 0
14 1   ",
header=TRUE,stringsAsFactors=FALSE,fill=TRUE)
phdf$R1<-ifelse(nchar(phdf$RunnerFirst) > 0,1,0)
phdf$R2<-ifelse(nchar(phdf$RunnerSecond) > 0,1,0)
phdf$R3<-ifelse(nchar(phdf$RunnerThird) > 0,1,0)

Jim

On Wed, Oct 23, 2019 at 7:54 AM Phillip Heinrich  wrote:
>
>   Row Outs RunnerFirst RunnerSecond RunnerThird R1 R2 R3
>   1 0
>   2 1
>   3 1
>   4 1 arenn001
>   5 2 arenn001
>   6 0
>   7 0 perad001
>   8 0 polla001 perad001
>   9 0 goldp001 polla001 perad001
>   10 0  lambj001 goldp001
>   11 1  lambj001 goldp001
>   12 2   lambj001
>   13 0
>   14 1
>
>
>
> With the above data, Arizona Diamondbacks baseball, I’m trying to put zeros 
> into the R1 column is the RunnerFirst column is blank and a one if the column 
> has a coded entry such as rows 4,5,7,8,& 9.  Similarly I want zeros in R2 and 
> R3 if RunnerSecond and RunnerThird respectively are blank and ones if there 
> is an entry.
>
> I’ve tried everything I know how to do such as “If Loops”, “If-Then loops”, 
> “apply”, “sapply”, etc.  I wrote function below and it ran without errors but 
> I have no idea what to do with it to accomplish my goal:
>
> R1 <- function(x) {
>   if (ari18.test3$RunnerFirst == " "){
>ari18.test3$R1 <- 0
>return(R1)
>  }else{
>R1 <- ari18.test3$R1 <- 1
>return(R1)
>  }
>}
>
> The name of the data frame is ari18.test3
>
> On a more philosophical note, data handling in R seems to be made up of 
> thousands of details with no over-riding principles.  I’ve read two books on 
> R and a number of tutorial and watched several videos but I don’t seem to be 
> making any progress.  Can anyone suggest videos, or tutorials, or books that 
> might help?  Database stuff has never been my strong point but I’m determined 
> to learn.
>
> Thanks,
> Philip Heinrich
> [[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.


[R] If Loop I Think

2019-10-22 Thread Phillip Heinrich
  Row Outs RunnerFirst RunnerSecond RunnerThird R1 R2 R3 
  1 0   
  2 1   
  3 1   
  4 1 arenn001  
  5 2 arenn001  
  6 0   
  7 0 perad001  
  8 0 polla001 perad001 
  9 0 goldp001 polla001 perad001
  10 0  lambj001 goldp001
  11 1  lambj001 goldp001
  12 2   lambj001
  13 0   
  14 1   



With the above data, Arizona Diamondbacks baseball, I’m trying to put zeros 
into the R1 column is the RunnerFirst column is blank and a one if the column 
has a coded entry such as rows 4,5,7,8,& 9.  Similarly I want zeros in R2 and 
R3 if RunnerSecond and RunnerThird respectively are blank and ones if there is 
an entry.  

I’ve tried everything I know how to do such as “If Loops”, “If-Then loops”, 
“apply”, “sapply”, etc.  I wrote function below and it ran without errors but I 
have no idea what to do with it to accomplish my goal:

R1 <- function(x) {  
  if (ari18.test3$RunnerFirst == " "){
   ari18.test3$R1 <- 0
   return(R1)
 }else{
   R1 <- ari18.test3$R1 <- 1
   return(R1)
 }
   }

The name of the data frame is ari18.test3

On a more philosophical note, data handling in R seems to be made up of 
thousands of details with no over-riding principles.  I’ve read two books on R 
and a number of tutorial and watched several videos but I don’t seem to be 
making any progress.  Can anyone suggest videos, or tutorials, or books that 
might help?  Database stuff has never been my strong point but I’m determined 
to learn.

Thanks,
Philip Heinrich
[[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] If Loop With Lagged Variable

2019-09-19 Thread Rui Barradas

Hello,

The following might be a better solution.
I include a minimal data set as an example.


Date <- c(rep(as.Date("2018-03-29"), 4),
  rep(as.Date("2018-03-30"), 4),
  rep(as.Date("2018-04-01"), 4))

ari18.test3 <- data.frame(Date)
ari18.test3$GameNum <- 1

#---

d <- c(0, diff(ari18.test3$Date) != 0)
ari18.test3$GameNum <- ari18.test3$GameNum + cumsum(d)

ari18.test3
# Date GameNum
#1  2018-03-29   1
#2  2018-03-29   1
#3  2018-03-29   1
#4  2018-03-29   1
#5  2018-03-30   2
#6  2018-03-30   2
#7  2018-03-30   2
#8  2018-03-30   2
#9  2018-04-01   3
#10 2018-04-01   3
#11 2018-04-01   3
#12 2018-04-01   3


Hope this helps,

Rui Barradas

Às 22:09 de 19/09/19, Rui Barradas escreveu:

Hello,

There was no attachment, R-Help allows only a limited number of file 
types, see the posting guide and try reposting.


As for the question, try ifelse, the vectorized fom of if/else.

ifelse(ari18.test3$Date > lag(ari18.test3$Date), ari18.tesm3$GameNum + 
1, ari18.test3$gameNum)



(Not tested, since there is no data.)

Hope this helps,

Rui Barradas

Às 17:27 de 19/09/19, Phillip Heinrich escreveu:
Attached is every at bat for the Arizona Diamondback’s first three 
games of 2018 – BBdata1.rda.  I added the Date and DHCode variables by 
parsing the first variable labeled GameID.


BBdata2 is a reduced dataset with five variables as shown in the str() 
command.


data.frame':    234 obs. of  5 variables:
  $ GameID : Factor w/ 3 levels "ARI201803290",..: 1 1 1 1 1 1 1 1 1 1 
...
  $ Date   : Date, format: "2018-03-29" "2018-03-29" "2018-03-29" 
"2018-03-29" ...

  $ DHCode : Factor w/ 1 level "0": 1 1 1 1 1 1 1 1 1 1 ...
  $ GameNum: num  1 1 1 1 1 1 1 1 1 1 ...
  $ Date2  : Date, format: NA "2018-03-29" "2018-03-29" "2018-03-29" ...
   I’m trying to increment the GameNum (game number) to game 2 when 
the date changes from 2018-03-29 to 2018-03-30 in row 81 and to game 3 
in row 165.


According to my R for Dummies book the following code should work but 
it doesn’t.  I keep getting the following error.  Any suggestions?


if(ari18.test3$Date > lag(ari18.test3$Date)) {ari18.test3$gameNum <- 
ari18.tesm3$GameNum + 1}

Warning message:
In if (ari18.test3$Date > lag(ari18.test3$Date)) { :
   the condition has length > 1 and only the first element will be used
 >


Thanks.
__
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] If Loop With Lagged Variable

2019-09-19 Thread Rui Barradas

Hello,

There was no attachment, R-Help allows only a limited number of file 
types, see the posting guide and try reposting.


As for the question, try ifelse, the vectorized fom of if/else.

ifelse(ari18.test3$Date > lag(ari18.test3$Date), ari18.tesm3$GameNum + 
1, ari18.test3$gameNum)



(Not tested, since there is no data.)

Hope this helps,

Rui Barradas

Às 17:27 de 19/09/19, Phillip Heinrich escreveu:

Attached is every at bat for the Arizona Diamondback’s first three games of 
2018 – BBdata1.rda.  I added the Date and DHCode variables by parsing the first 
variable labeled GameID.

BBdata2 is a reduced dataset with five variables as shown in the str() command.

data.frame':234 obs. of  5 variables:
  $ GameID : Factor w/ 3 levels "ARI201803290",..: 1 1 1 1 1 1 1 1 1 1 ...
  $ Date   : Date, format: "2018-03-29" "2018-03-29" "2018-03-29" "2018-03-29" 
...
  $ DHCode : Factor w/ 1 level "0": 1 1 1 1 1 1 1 1 1 1 ...
  $ GameNum: num  1 1 1 1 1 1 1 1 1 1 ...
  $ Date2  : Date, format: NA "2018-03-29" "2018-03-29" "2018-03-29" ...
   I’m trying to increment the GameNum (game number) to game 2 when the date 
changes from 2018-03-29 to 2018-03-30 in row 81 and to game 3 in row 165.

According to my R for Dummies book the following code should work but it 
doesn’t.  I keep getting the following error.  Any suggestions?

if(ari18.test3$Date > lag(ari18.test3$Date)) {ari18.test3$gameNum <- 
ari18.tesm3$GameNum + 1}
Warning message:
In if (ari18.test3$Date > lag(ari18.test3$Date)) { :
   the condition has length > 1 and only the first element will be used
  
  
 >
  



Thanks.
__
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] If Loop With Lagged Variable

2019-09-19 Thread Phillip Heinrich
Attached is every at bat for the Arizona Diamondback’s first three games of 
2018 – BBdata1.rda.  I added the Date and DHCode variables by parsing the first 
variable labeled GameID.

BBdata2 is a reduced dataset with five variables as shown in the str() command.

data.frame':234 obs. of  5 variables:
 $ GameID : Factor w/ 3 levels "ARI201803290",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ Date   : Date, format: "2018-03-29" "2018-03-29" "2018-03-29" "2018-03-29" 
...
 $ DHCode : Factor w/ 1 level "0": 1 1 1 1 1 1 1 1 1 1 ...
 $ GameNum: num  1 1 1 1 1 1 1 1 1 1 ...
 $ Date2  : Date, format: NA "2018-03-29" "2018-03-29" "2018-03-29" ...
  I’m trying to increment the GameNum (game number) to game 2 when the date 
changes from 2018-03-29 to 2018-03-30 in row 81 and to game 3 in row 165.

According to my R for Dummies book the following code should work but it 
doesn’t.  I keep getting the following error.  Any suggestions?

if(ari18.test3$Date > lag(ari18.test3$Date)) {ari18.test3$gameNum <- 
ari18.tesm3$GameNum + 1}
Warning message:
In if (ari18.test3$Date > lag(ari18.test3$Date)) { :
  the condition has length > 1 and only the first element will be used
 
 
>  
 


Thanks.
__
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] loop de mapas

2019-09-14 Thread Manuel Mendoza
Buenas tardes. Intento hacer 6 mapas en un loop, de acuerdo, cada uno de
ellos, a una de 6 variables recogidas en el vector GT:

GT<-c("IIFd5026","IIFd5045","IIFd5085","IIFd7026","IIFd7045","IIFd7085")

for(i in GT) {

  NCDS <- NCDS[NCDS[[i]] > 0,]

windows();print(ggplot(legend=FALSE)+geom_path( data=world, aes(x=long,
y=lat,group=group))+
theme(panel.background=element_blank())+theme(panel.grid.major =
element_blank())+
theme(panel.grid.minor =
element_blank())+theme(axis.text.x=element_blank(),axis.text.y=element_blank())+
theme(axis.ticks = element_blank())+xlab("") + ylab("")+
geom_point(data=NCDS,aes(x=lon,y=lat,*color = (GT[i]))*,size=2) +

scale_colour_gradient(low=("white"),high=("red"),guide="colourbar",limits=c(0,max))+
geom_path(data=map_data('world'), aes(x=long, y=lat,group=group))+
labs(title =  paste(GT[i],"Minimum number of IFd species to go
extinct")))

}

Si en vez de  color = (GT[i]) pongo  color = IIFd5026 (primer elemento del
vector GT) sale bien, pero, de la primera forma me da error:

Error: Discrete value supplied to continuous scale

He probado con  color = GT[i],  color = i y otras formas, por si acaso,
pero no funciona.

Muchas gracias, como siempre,
Manuel

[[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] For Loop

2018-09-25 Thread Martin Maechler
> Wensui Liu 
> on Sun, 23 Sep 2018 13:26:32 -0500 writes:

> what you measures is the "elapsed" time in the default
> setting. you might need to take a closer look at the
> beautiful benchmark() function and see what time I am
> talking about.

> I just provided tentative solution for the person asking
> for it and believe he has enough wisdom to decide what's
> best. why bother to judge others subjectively?  

Well, because  Ista Zahn is much much much better R programmer
than you, sorry to be blunt!

Martin

> On Sun, Sep 23, 2018 at 1:18 PM Ista Zahn 
> wrote:
>> 
>> On Sun, Sep 23, 2018 at 1:46 PM Wensui Liu
>>  wrote:
>> >
>> > actually, by the parallel pvec, the user time is a lot
>> shorter. or did > I somewhere miss your invaluable
>> insight?
>> >
>> > > c1 <- 1:100 > > len <- length(c1) > >
>> rbenchmark::benchmark(log(c1[-1]/c1[-len]), replications
>> = 100) > test replications elapsed relative user.self
>> sys.self > 1 log(c1[-1]/c1[-len]) 100 4.617 1 4.484 0.133
>> > user.child sys.child > 1 0 0 > >
>> rbenchmark::benchmark(pvec(1:(len - 1), mc.cores = 4,
>> function(i) log(c1[i + 1] / c1[i])), replications = 100)
>> > test > 1 pvec(1:(len - 1), mc.cores = 4, function(i)
>> log(c1[i + 1]/c1[i])) > replications elapsed relative
>> user.self sys.self user.child sys.child > 1 100 9.079 1
>> 2.571 4.138 9.736 8.046
>> 
>> Your output is mangled in my email, but on my system your
>> pvec approach takes more than twice as long:
>> 
>> c1 <- 1:100 len <- length(c1) library(parallel)
>> library(rbenchmark)
>> 
>> regular <- function() log(c1[-1]/c1[-len])
>> iterate.parallel <- function() { pvec(1:(len - 1),
>> mc.cores = 4, function(i) log(c1[i + 1] / c1[i])) }
>> 
>> benchmark(regular(), iterate.parallel(), replications =
>> 100, columns = c("test", "elapsed", "relative")) ## test
>> elapsed relative ## 2 iterate.parallel() 7.517 2.482 ## 1
>> regular() 3.028 1.000
>> 
>> Honestly, just use log(c1[-1]/c1[-len]). The code is
>> simple and easy to understand and it runs pretty
>> fast. There is usually no reason to make it more
>> complicated.  --Ista
>> 
>> > On Sun, Sep 23, 2018 at 12:33 PM Ista Zahn
>>  wrote:
>> > >
>> > > On Sun, Sep 23, 2018 at 10:09 AM Wensui Liu
>>  wrote:
>> > > >
>> > > > Why?
>> > >
>> > > The operations required for this algorithm are
>> vectorized, as are most > > operations in R. There is no
>> need to iterate through each element.  > > Using
>> Vectorize to achieve the iteration is no better than
>> using > > *apply or a for-loop, and betrays the same
>> basic lack of insight into > > basic principles of
>> programming in R.
>> > >
>> > > And/or, if you want a more practical reason:
>> > >
>> > > > c1 <- 1:100 > > > len <- 100 > > >
>> system.time( s1 <- log(c1[-1]/c1[-len])) > > user system
>> elapsed > > 0.031 0.004 0.035 > > > system.time(s2 <-
>> Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len)) >
>> > user system elapsed > > 1.258 0.022 1.282
>> > >
>> > > Best, > > Ista
>> > >
>> > > >
>> > > > On Sun, Sep 23, 2018 at 7:54 AM Ista Zahn
>>  wrote:
>> > > >>
>> > > >> On Sat, Sep 22, 2018 at 9:06 PM Wensui Liu
>>  wrote:
>> > > >> >
>> > > >> > or this one:
>> > > >> >
>> > > >> > (Vectorize(function(i) log(c1[i + 1] / c1[i]))
>> (1:len))
>> > > >>
>> > > >> Oh dear god no.
>> > > >>
>> > > >> >
>> > > >> > On Sat, Sep 22, 2018 at 4:16 PM rsherry8
>>  wrote:
>> > > >> > >
>> > > >> > >
>> > > >> > > It is my impression that good R programmers
>> make very little use of the > > >> > > for
>> statement. Please consider the following > > >> > > R
>> statement: > > >> > > for( i in 1:(len-1) ) s[i] =
>> log(c1[i+1]/c1[i], base = exp(1) ) > > >> > > One problem
>> I have found with this statement is that s must exist
>> before > > >> > > the statement is run. Can it be written
>> without using a for > > >> > > loop? Would that be
>> better?
>> > > >> > >
>> > > >> > > Thanks, > > >> > > Bob
>> > > >> > >
>> > > >> > > __
>> > > >> > > 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 > > >> >
>> 

Re: [R] For Loop

2018-09-24 Thread J C Nash
One issue I haven't seen mentioned (and apologize if I've missed it) is that
of making programs readable for long-term use. In the histoRicalg project to
try to document and test some of the codes from long ago that are the 
underpinnings
of some important R computations, things like the negative index approach 
require
what we might term "local knowledge" i.e., to R. In such cases the old fashioned
for loop is easier for humans to understand.

The i:j form is a bit easier.

Compromise is to comment, and if your code is EVER to be used later, especially
by non-R users, it is a good idea to do so.

i.e.,

 c1[-1] # does loop from 2 to end of vector

John Nash

histoRicalg links, to which all welcome:
https://gitlab.com/nashjc/histoRicalg
https://gitlab.com/nashjc/histoRicalg/wikis/home
https://lists.r-consortium.org/g/rconsortium-project-histoRicalg

On 2018-09-24 12:13 PM, MacQueen, Don via R-help wrote:
> In my opinion this is a pretty reasonable question for someone new to R.
> 
> Yes, it can be written without a for loop, and it would be better. Rich 
> Heiberger gave a good solution early on, but I'd like to add an outline of 
> the reasoning that leads to the solution.
> 
> You are taking the log of a ratio, and in the ratio, the numerator uses 
> elements 2 through len, and the denominator uses elements 1 through (len-1). 
> So, just write it that way:
> 
>c1[2:len]/c1[1:(len-1)]
> 
> or, taking advantage of using negative numbers when indexing vectors,
> 
>c1[-1]/c1[-len]
> 
> then take the log
> 
>s <- log( c1[-1]/c1[-len] )
> 
> Comparing this with the loop version makes an example of why people say the R 
> language is vectorized.
> 
> Do good R programmers make very little use of the for statement? Since R is 
> vectorized, the for statement is necessary less often than in  non-vectorized 
> languages. But "very little use" would be too broad a generalization. It will 
> depend on what problems are being solved.
> 
> Finally, if using the loop in this case, it's true that s must exist before 
> the statement is run. But that's not much of a problem. Just put
>   s <- numeric( len-1)
> before the loop.
> 
> --
> Don MacQueen
> Lawrence Livermore National Laboratory
> 7000 East Ave., L-627
> Livermore, CA 94550
> 925-423-1062
> Lab cell 925-724-7509
>  
>  
> 
> On 9/22/18, 2:16 PM, "R-help on behalf of rsherry8" 
>  wrote:
> 
> 
> It is my impression that good R programmers make very little use of the 
> for statement. Please consider  the following
> R statement:
>  for( i in 1:(len-1) )  s[i] = log(c1[i+1]/c1[i], base = exp(1) )
> One problem I have found with this statement is that s must exist before 
> the statement is run. Can it be written without using a for
> loop? Would that be better?
> 
> Thanks,
> Bob
> 
> __
> 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] For Loop

2018-09-24 Thread MacQueen, Don via R-help
In my opinion this is a pretty reasonable question for someone new to R.

Yes, it can be written without a for loop, and it would be better. Rich 
Heiberger gave a good solution early on, but I'd like to add an outline of the 
reasoning that leads to the solution.

You are taking the log of a ratio, and in the ratio, the numerator uses 
elements 2 through len, and the denominator uses elements 1 through (len-1). 
So, just write it that way:

   c1[2:len]/c1[1:(len-1)]

or, taking advantage of using negative numbers when indexing vectors,

   c1[-1]/c1[-len]

then take the log

   s <- log( c1[-1]/c1[-len] )

Comparing this with the loop version makes an example of why people say the R 
language is vectorized.

Do good R programmers make very little use of the for statement? Since R is 
vectorized, the for statement is necessary less often than in  non-vectorized 
languages. But "very little use" would be too broad a generalization. It will 
depend on what problems are being solved.

Finally, if using the loop in this case, it's true that s must exist before the 
statement is run. But that's not much of a problem. Just put
  s <- numeric( len-1)
before the loop.

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

On 9/22/18, 2:16 PM, "R-help on behalf of rsherry8" 
 wrote:


It is my impression that good R programmers make very little use of the 
for statement. Please consider  the following
R statement:
 for( i in 1:(len-1) )  s[i] = log(c1[i+1]/c1[i], base = exp(1) )
One problem I have found with this statement is that s must exist before 
the statement is run. Can it be written without using a for
loop? Would that be better?

Thanks,
Bob

__
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] For Loop

2018-09-23 Thread Bert Gunter
"... I learned to say "try it and see" in many different ways. "

Version 2: *Never* parallelize your computations   except when you
should.

;-)

-- Bert



On Sun, Sep 23, 2018 at 1:20 PM Duncan Murdoch 
wrote:

> On 23/09/2018 4:00 PM, Wensui Liu wrote:
> > Very insightful. Thanks, Duncan
> >
> > Based on your opinion, is there any benefit to use the parallelism in
> > the corporate computing environment where the size of data is far more
> > than million rows and there are multiple cores in the server.
>
> I would say "try it and see".  Sometimes it probably helps a lot,
> sometimes it's probably detrimental.
>
> Duncan Murdoch
>
> P.S. I last worked in a corporate computing environment 40 years ago
> when I was still wet behind the ears, so you'd probably want to ask
> someone else.  However, more recently I worked in an academic
> environment where I learned to say "try it and see" in many different
> ways.  You just got the basic one today.
>
>
> >
> > Actually the practice of going concurrency or not is more related to my
> > production tasks instead of something academic.
> >
> > Really appreciate your thoughts.
> >
> > On Sun, Sep 23, 2018 at 2:42 PM Duncan Murdoch  > > wrote:
> >
> > On 23/09/2018 3:31 PM, Jeff Newmiller wrote:
> >
> > [lots of good stuff deleted]
> >
> >  > Vectorize is
> >  > syntactic sugar with a performance penalty.
> >
> > [More deletions.]
> >
> > I would say Vectorize isn't just "syntactic sugar".  When I use that
> > term, I mean something that looks nice but is functionally
> equivalent.
> >
> > However, Vectorize() really does something useful:  some functions
> > (e.g.
> > outer()) take other functions as arguments, but they assume the
> > argument
> > is a vectorized function.  If it is not, they fail, or generate
> garbage
> > results.  Vectorize() is designed to modify the interface to a
> function
> > so it acts as if it is vectorized.
> >
> > The "performance penalty" part of your statement is true.  It will
> > generally save some computing cycles to write a new function using a
> > for
> > loop instead of using Vectorize().  But that may waste some
> > programmer time.
> >
> > Duncan Murdoch
> > (writing as one of the authors of Vectorize())
> >
> > P.S. I'd give an example of syntactic sugar, but I don't want to
> bruise
> > some other author's feelings :-).
> >
>
> __
> 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] For Loop

2018-09-23 Thread Duncan Murdoch

On 23/09/2018 4:00 PM, Wensui Liu wrote:

Very insightful. Thanks, Duncan

Based on your opinion, is there any benefit to use the parallelism in 
the corporate computing environment where the size of data is far more 
than million rows and there are multiple cores in the server.


I would say "try it and see".  Sometimes it probably helps a lot, 
sometimes it's probably detrimental.


Duncan Murdoch

P.S. I last worked in a corporate computing environment 40 years ago 
when I was still wet behind the ears, so you'd probably want to ask 
someone else.  However, more recently I worked in an academic 
environment where I learned to say "try it and see" in many different 
ways.  You just got the basic one today.





Actually the practice of going concurrency or not is more related to my 
production tasks instead of something academic.


Really appreciate your thoughts.

On Sun, Sep 23, 2018 at 2:42 PM Duncan Murdoch > wrote:


On 23/09/2018 3:31 PM, Jeff Newmiller wrote:

[lots of good stuff deleted]

 > Vectorize is
 > syntactic sugar with a performance penalty.

[More deletions.]

I would say Vectorize isn't just "syntactic sugar".  When I use that
term, I mean something that looks nice but is functionally equivalent.

However, Vectorize() really does something useful:  some functions
(e.g.
outer()) take other functions as arguments, but they assume the
argument
is a vectorized function.  If it is not, they fail, or generate garbage
results.  Vectorize() is designed to modify the interface to a function
so it acts as if it is vectorized.

The "performance penalty" part of your statement is true.  It will
generally save some computing cycles to write a new function using a
for
loop instead of using Vectorize().  But that may waste some
programmer time.

Duncan Murdoch
(writing as one of the authors of Vectorize())

P.S. I'd give an example of syntactic sugar, but I don't want to bruise
some other author's feelings :-).



__
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] For Loop

2018-09-23 Thread Wensui Liu
Very insightful. Thanks, Duncan

Based on your opinion, is there any benefit to use the parallelism in the
corporate computing environment where the size of data is far more than
million rows and there are multiple cores in the server.

Actually the practice of going concurrency or not is more related to my
production tasks instead of something academic.

Really appreciate your thoughts.

On Sun, Sep 23, 2018 at 2:42 PM Duncan Murdoch 
wrote:

> On 23/09/2018 3:31 PM, Jeff Newmiller wrote:
>
> [lots of good stuff deleted]
>
> > Vectorize is
> > syntactic sugar with a performance penalty.
>
> [More deletions.]
>
> I would say Vectorize isn't just "syntactic sugar".  When I use that
> term, I mean something that looks nice but is functionally equivalent.
>
> However, Vectorize() really does something useful:  some functions (e.g.
> outer()) take other functions as arguments, but they assume the argument
> is a vectorized function.  If it is not, they fail, or generate garbage
> results.  Vectorize() is designed to modify the interface to a function
> so it acts as if it is vectorized.
>
> The "performance penalty" part of your statement is true.  It will
> generally save some computing cycles to write a new function using a for
> loop instead of using Vectorize().  But that may waste some programmer
> time.
>
> Duncan Murdoch
> (writing as one of the authors of Vectorize())
>
> P.S. I'd give an example of syntactic sugar, but I don't want to bruise
> some other author's feelings :-).
>

[[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] For Loop

2018-09-23 Thread Jeff Newmiller

On Sun, 23 Sep 2018, Duncan Murdoch wrote:


On 23/09/2018 3:31 PM, Jeff Newmiller wrote:

[lots of good stuff deleted]


Vectorize is
syntactic sugar with a performance penalty.


[More deletions.]

I would say Vectorize isn't just "syntactic sugar".  When I use that term, I 
mean something that looks nice but is functionally equivalent.


However, Vectorize() really does something useful:  some functions (e.g. 
outer()) take other functions as arguments, but they assume the argument is a 
vectorized function.  If it is not, they fail, or generate garbage results. 
Vectorize() is designed to modify the interface to a function so it acts as 
if it is vectorized.


The "performance penalty" part of your statement is true.  It will generally 
save some computing cycles to write a new function using a for loop instead 
of using Vectorize().  But that may waste some programmer time.


Duncan Murdoch
(writing as one of the authors of Vectorize())

P.S. I'd give an example of syntactic sugar, but I don't want to bruise some 
other author's feelings :-).


Perhaps my writing needs some syntactic sugar: inefficient looping 
algorithms can make sense when the calculations performed in each 
iteration are long and/or involve large amounts of data. As I mentioned 
earlier in this thread I use for loops fairly often, and I use other 
inefficient syntactic sugar as well but only to organize large 
blocks of already-vectorized (lowercase) calculation units.


In addition to the potential for inefficient use of programmer time, 
vectorizing code increases the maximum amount of memory used during 
execution of your program. A for loop is one simple way to allow memory 
re-use so really large problems can be solved with limited resources, and 
some syntactic sugar such as Vectorize can make it easier to keep track of 
those for loops.


---
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] For Loop

2018-09-23 Thread Duncan Murdoch

On 23/09/2018 3:31 PM, Jeff Newmiller wrote:

[lots of good stuff deleted]


Vectorize is
syntactic sugar with a performance penalty.


[More deletions.]

I would say Vectorize isn't just "syntactic sugar".  When I use that 
term, I mean something that looks nice but is functionally equivalent.


However, Vectorize() really does something useful:  some functions (e.g. 
outer()) take other functions as arguments, but they assume the argument 
is a vectorized function.  If it is not, they fail, or generate garbage 
results.  Vectorize() is designed to modify the interface to a function 
so it acts as if it is vectorized.


The "performance penalty" part of your statement is true.  It will 
generally save some computing cycles to write a new function using a for 
loop instead of using Vectorize().  But that may waste some programmer time.


Duncan Murdoch
(writing as one of the authors of Vectorize())

P.S. I'd give an example of syntactic sugar, but I don't want to bruise 
some other author's feelings :-).


__
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] For Loop

2018-09-23 Thread Jeff Newmiller

On Sun, 23 Sep 2018, Wensui Liu wrote:


what you measures is the "elapsed" time in the default setting. you
might need to take a closer look at the beautiful benchmark() function
and see what time I am talking about.


When I am waiting for the answer, elapsed time is what matters to me. 
Also, since each person usually has different hardware, running benchmark 
with multiple expressions as Ista did lets you pay attention to relative 
comparisons.


Keep in mind that parallel processing requires extra time just to 
distribute the calculations to the workers, so it doesn't pay to 
distribute tiny tasks like calculating the division of two numeric vector 
elements. That is the essence of vectorizing... bundle your simple 
calculations together so the processor can focus on getting answers rather 
than managing processes or even interpreting R for loops.



I just provided tentative solution for the person asking for it  and
believe he has enough wisdom to decide what's best. why bother to
judge others subjectively?


I would say that Ista has backed up his objections with measurable 
performance metrics, so while his initial reaction was pretty subjective I 
think your reaction at this point is really off the mark.


One confusing aspect of your response is that Ista reacted to your 
use of the Vectorize function, but you responded as though he reacted 
to your use of the pvec function. I mentioned drawbacks of using pvec 
above, but it really is important to stress that the Vectorize function is 
a usability facade and is in no way a performance enhancement to be 
associated with what we refer to as vectorized (lowercase) code.


The Vectorize function creates a function that calls lapply, which in turn 
calls the C function do_lapply, which calls your R function with scalar 
inputs as many times as desired, storing the results in a list, which 
Vectorize then gives to mapply which runs another for loop over to create 
a matrix or vector result. This is clearly less efficient than a simple 
for loop would have been, rather than more efficient as a true vectorized 
solution such as log(c1[-1]/c1[-len]) will normally be. Vectorize is 
syntactic sugar with a performance penalty.


Please pay attention to the comments offered by others on this list... 
being told your solution is inferior doesn't feel good but it is a very 
real opportunity for you to improve.


End comment.


On Sun, Sep 23, 2018 at 1:18 PM Ista Zahn  wrote:


On Sun, Sep 23, 2018 at 1:46 PM Wensui Liu  wrote:


actually, by the parallel pvec, the user time is a lot shorter. or did
I somewhere miss your invaluable insight?


c1 <- 1:100
len <- length(c1)
rbenchmark::benchmark(log(c1[-1]/c1[-len]), replications = 100)

  test replications elapsed relative user.self sys.self
1 log(c1[-1]/c1[-len])  100   4.6171 4.4840.133
  user.child sys.child
1  0 0

rbenchmark::benchmark(pvec(1:(len - 1), mc.cores = 4, function(i) log(c1[i + 1] 
/ c1[i])), replications = 100)

   test
1 pvec(1:(len - 1), mc.cores = 4, function(i) log(c1[i + 1]/c1[i]))
  replications elapsed relative user.self sys.self user.child sys.child
1  100   9.0791 2.5714.138  9.736 8.046


Your output is mangled in my email, but on my system your pvec
approach takes more than twice as long:

c1 <- 1:100
len <- length(c1)
library(parallel)
library(rbenchmark)

regular <- function() log(c1[-1]/c1[-len])
iterate.parallel <- function() {
  pvec(1:(len - 1), mc.cores = 4,
   function(i) log(c1[i + 1] / c1[i]))
}

benchmark(regular(), iterate.parallel(),
  replications = 100,
  columns = c("test", "elapsed", "relative"))
## test elapsed relative
## 2 iterate.parallel()   7.5172.482
## 1  regular()   3.0281.000

Honestly, just use log(c1[-1]/c1[-len]). The code is simple and easy
to understand and it runs pretty fast. There is usually no reason to
make it more complicated.
--Ista


On Sun, Sep 23, 2018 at 12:33 PM Ista Zahn  wrote:


On Sun, Sep 23, 2018 at 10:09 AM Wensui Liu  wrote:


Why?


The operations required for this algorithm are vectorized, as are most
operations in R. There is no need to iterate through each element.
Using Vectorize to achieve the iteration is no better than using
*apply or a for-loop, and betrays the same basic lack of insight into
basic principles of programming in R.

And/or, if you want a more practical reason:


c1 <- 1:100
len <- 100
system.time( s1 <- log(c1[-1]/c1[-len]))

   user  system elapsed
  0.031   0.004   0.035

system.time(s2 <- Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))

   user  system elapsed
  1.258   0.022   1.282

Best,
Ista



On Sun, Sep 23, 2018 at 7:54 AM Ista Zahn  wrote:


On Sat, Sep 22, 2018 at 9:06 PM Wensui Liu  wrote:


or this one:

(Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))


Oh dear god 

Re: [R] For Loop

2018-09-23 Thread Ista Zahn
On Sun, Sep 23, 2018 at 2:26 PM Wensui Liu  wrote:
>
> what you measures is the "elapsed" time in the default setting. you
> might need to take a closer look at the beautiful benchmark() function
> and see what time I am talking about.

I'm pretty sure you do not know what you are talking about.

>
> I just provided tentative solution for the person asking for it  and
> believe he has enough wisdom to decide what's best. why bother to
> judge others subjectively?

You are giving bad and confused advice. Please stop doing that.

--Ista

> On Sun, Sep 23, 2018 at 1:18 PM Ista Zahn  wrote:
> >
> > On Sun, Sep 23, 2018 at 1:46 PM Wensui Liu  wrote:
> > >
> > > actually, by the parallel pvec, the user time is a lot shorter. or did
> > > I somewhere miss your invaluable insight?
> > >
> > > > c1 <- 1:100
> > > > len <- length(c1)
> > > > rbenchmark::benchmark(log(c1[-1]/c1[-len]), replications = 100)
> > >   test replications elapsed relative user.self sys.self
> > > 1 log(c1[-1]/c1[-len])  100   4.6171 4.4840.133
> > >   user.child sys.child
> > > 1  0 0
> > > > rbenchmark::benchmark(pvec(1:(len - 1), mc.cores = 4, function(i) 
> > > > log(c1[i + 1] / c1[i])), replications = 100)
> > >test
> > > 1 pvec(1:(len - 1), mc.cores = 4, function(i) log(c1[i + 1]/c1[i]))
> > >   replications elapsed relative user.self sys.self user.child sys.child
> > > 1  100   9.0791 2.5714.138  9.736 8.046
> >
> > Your output is mangled in my email, but on my system your pvec
> > approach takes more than twice as long:
> >
> > c1 <- 1:100
> > len <- length(c1)
> > library(parallel)
> > library(rbenchmark)
> >
> > regular <- function() log(c1[-1]/c1[-len])
> > iterate.parallel <- function() {
> >   pvec(1:(len - 1), mc.cores = 4,
> >function(i) log(c1[i + 1] / c1[i]))
> > }
> >
> > benchmark(regular(), iterate.parallel(),
> >   replications = 100,
> >   columns = c("test", "elapsed", "relative"))
> > ## test elapsed relative
> > ## 2 iterate.parallel()   7.5172.482
> > ## 1  regular()   3.0281.000
> >
> > Honestly, just use log(c1[-1]/c1[-len]). The code is simple and easy
> > to understand and it runs pretty fast. There is usually no reason to
> > make it more complicated.
> > --Ista
> >
> > > On Sun, Sep 23, 2018 at 12:33 PM Ista Zahn  wrote:
> > > >
> > > > On Sun, Sep 23, 2018 at 10:09 AM Wensui Liu  wrote:
> > > > >
> > > > > Why?
> > > >
> > > > The operations required for this algorithm are vectorized, as are most
> > > > operations in R. There is no need to iterate through each element.
> > > > Using Vectorize to achieve the iteration is no better than using
> > > > *apply or a for-loop, and betrays the same basic lack of insight into
> > > > basic principles of programming in R.
> > > >
> > > > And/or, if you want a more practical reason:
> > > >
> > > > > c1 <- 1:100
> > > > > len <- 100
> > > > > system.time( s1 <- log(c1[-1]/c1[-len]))
> > > >user  system elapsed
> > > >   0.031   0.004   0.035
> > > > > system.time(s2 <- Vectorize(function(i) log(c1[i + 1] / c1[i])) 
> > > > > (1:len))
> > > >user  system elapsed
> > > >   1.258   0.022   1.282
> > > >
> > > > Best,
> > > > Ista
> > > >
> > > > >
> > > > > On Sun, Sep 23, 2018 at 7:54 AM Ista Zahn  wrote:
> > > > >>
> > > > >> On Sat, Sep 22, 2018 at 9:06 PM Wensui Liu  
> > > > >> wrote:
> > > > >> >
> > > > >> > or this one:
> > > > >> >
> > > > >> > (Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))
> > > > >>
> > > > >> Oh dear god no.
> > > > >>
> > > > >> >
> > > > >> > On Sat, Sep 22, 2018 at 4:16 PM rsherry8  
> > > > >> > wrote:
> > > > >> > >
> > > > >> > >
> > > > >> > > It is my impression that good R programmers make very little use 
> > > > >> > > of the
> > > > >> > > for statement. Please consider  the following
> > > > >> > > R statement:
> > > > >> > >  for( i in 1:(len-1) )  s[i] = log(c1[i+1]/c1[i], base = 
> > > > >> > > exp(1) )
> > > > >> > > One problem I have found with this statement is that s must 
> > > > >> > > exist before
> > > > >> > > the statement is run. Can it be written without using a for
> > > > >> > > loop? Would that be better?
> > > > >> > >
> > > > >> > > Thanks,
> > > > >> > > Bob
> > > > >> > >
> > > > >> > > __
> > > > >> > > 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
> > > > >> > 

Re: [R] For Loop

2018-09-23 Thread Jeff Newmiller

Below...

On Sun, 23 Sep 2018, Sorkin, John wrote:


At the risk of asking something fundamental . . . .

does log(c1[-1]/c1[-len]


You dropped the closing parenthesis.

log( c1[-1] / c1[-len] )



do the following


(1) use all elements of c and perform the calculation


No. a) "c" is the base "concatenate" function, and b) it is using two 
different subsets of the elements in c1.



(2) delete the first element of c and perform the calculation,


It does not change c1. c1[-1] is an expression that creates an entirely 
new (but unnamed) vector that contains everything but the first element of 
c1.



(2) delete the first two elements of c and perform the calculation,


You are wandering into the weeds here...


. . .

(n) use only the last element of c and perform the calculation.


No, c1[-len] creates a temporary array that contains all elements except 
the one(s) in the variable "len".  Note that the more conventional syntax 
here is c1[ length(c1) ].


c1 <- 1:3
c1[ -1 ]
#> [1] 2 3
c1[ -length(c1) ]
#> [1] 1 2
c1[ -1 ] / c1[ -length( c1 ) ] # c(2,3)/c(1,2)
#> [1] 2.0 1.5
log( c1[ -1 ] / c1[ -length( c1 ) ] ) # log( c(2, 1.5) )
#> [1] 0.6931472 0.4054651

#' Created on 2018-09-23 by the [reprex package](http://reprex.tidyverse.org) 
(v0.2.0).




Thank you,

John



John David Sorkin M.D., Ph.D.
Professor of Medicine
Chief, Biostatistics and Informatics
University of Maryland School of Medicine Division of Gerontology and Geriatric 
Medicine
Baltimore VA Medical Center
10 North Greene Street
GRECC (BT/18/GR)
Baltimore, MD 21201-1524
(Phone) 410-605-7119
(Fax) 410-605-7913 (Please call phone number above prior to faxing)




From: R-help  on behalf of Wensui Liu 

Sent: Sunday, September 23, 2018 2:26 PM
To: Ista Zahn
Cc: r-help@r-project.org
Subject: Re: [R] For Loop

CAUTION: This message originated from a non UMB, UMSOM, FPI, or UMMS email 
system. Whether the sender is known or not known, hover over any links before 
clicking and use caution opening attachments.



what you measures is the "elapsed" time in the default setting. you
might need to take a closer look at the beautiful benchmark() function
and see what time I am talking about.

I just provided tentative solution for the person asking for it  and
believe he has enough wisdom to decide what's best. why bother to
judge others subjectively?
On Sun, Sep 23, 2018 at 1:18 PM Ista Zahn  wrote:


On Sun, Sep 23, 2018 at 1:46 PM Wensui Liu  wrote:


actually, by the parallel pvec, the user time is a lot shorter. or did
I somewhere miss your invaluable insight?


c1 <- 1:100
len <- length(c1)
rbenchmark::benchmark(log(c1[-1]/c1[-len]), replications = 100)

  test replications elapsed relative user.self sys.self
1 log(c1[-1]/c1[-len])  100   4.6171 4.4840.133
  user.child sys.child
1  0 0

rbenchmark::benchmark(pvec(1:(len - 1), mc.cores = 4, function(i) log(c1[i + 1] 
/ c1[i])), replications = 100)

   test
1 pvec(1:(len - 1), mc.cores = 4, function(i) log(c1[i + 1]/c1[i]))
  replications elapsed relative user.self sys.self user.child sys.child
1  100   9.0791 2.5714.138  9.736 8.046


Your output is mangled in my email, but on my system your pvec
approach takes more than twice as long:

c1 <- 1:100
len <- length(c1)
library(parallel)
library(rbenchmark)

regular <- function() log(c1[-1]/c1[-len])
iterate.parallel <- function() {
  pvec(1:(len - 1), mc.cores = 4,
   function(i) log(c1[i + 1] / c1[i]))
}

benchmark(regular(), iterate.parallel(),
  replications = 100,
  columns = c("test", "elapsed", "relative"))
## test elapsed relative
## 2 iterate.parallel()   7.5172.482
## 1  regular()   3.0281.000

Honestly, just use log(c1[-1]/c1[-len]). The code is simple and easy
to understand and it runs pretty fast. There is usually no reason to
make it more complicated.
--Ista


On Sun, Sep 23, 2018 at 12:33 PM Ista Zahn  wrote:


On Sun, Sep 23, 2018 at 10:09 AM Wensui Liu  wrote:


Why?


The operations required for this algorithm are vectorized, as are most
operations in R. There is no need to iterate through each element.
Using Vectorize to achieve the iteration is no better than using
*apply or a for-loop, and betrays the same basic lack of insight into
basic principles of programming in R.

And/or, if you want a more practical reason:


c1 <- 1:100
len <- 100
system.time( s1 <- log(c1[-1]/c1[-len]))

   user  system elapsed
  0.031   0.004   0.035

system.time(s2 <- Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))

   user  system elapsed
  1.258   0.022   1.282

Best,
Ista



On Sun, Sep 23, 2018 at 7:54 AM Ista Zahn  wrote:


On Sat, Sep 22, 2018 at 9:06 PM Wensui Liu  wrote:


or t

Re: [R] For Loop

2018-09-23 Thread Duncan Murdoch

On 23/09/2018 2:36 PM, Sorkin, John wrote:

At the risk of asking something fundamental . . . .

does log(c1[-1]/c1[-len]

do the following


(1) use all elements of c and perform the calculation

(2) delete the first element of c and perform the calculation,

(2) delete the first two elements of c and perform the calculation,

  . . .

(n) use only the last element of c and perform the calculation.


c1[-1] creates a new vector which is a copy of c1 leaving out element 1, 
and c1[-len] creates a new vector which copies everything except element 
len.  So your (1) is closest to the truth.


It is very similar to (but probably a little faster than)

log(c1[2:len]/c1[1:(len-1)])

There are differences in borderline cases (like length(c1) != len, or 
len < 2) that are not relevant in the original context.


Duncan Murdoch



Thank you,

John



John David Sorkin M.D., Ph.D.
Professor of Medicine
Chief, Biostatistics and Informatics
University of Maryland School of Medicine Division of Gerontology and Geriatric 
Medicine
Baltimore VA Medical Center
10 North Greene Street
GRECC (BT/18/GR)
Baltimore, MD 21201-1524
(Phone) 410-605-7119
(Fax) 410-605-7913 (Please call phone number above prior to faxing)




From: R-help  on behalf of Wensui Liu 

Sent: Sunday, September 23, 2018 2:26 PM
To: Ista Zahn
Cc: r-help@r-project.org
Subject: Re: [R] For Loop

CAUTION: This message originated from a non UMB, UMSOM, FPI, or UMMS email 
system. Whether the sender is known or not known, hover over any links before 
clicking and use caution opening attachments.



what you measures is the "elapsed" time in the default setting. you
might need to take a closer look at the beautiful benchmark() function
and see what time I am talking about.

I just provided tentative solution for the person asking for it  and
believe he has enough wisdom to decide what's best. why bother to
judge others subjectively?
On Sun, Sep 23, 2018 at 1:18 PM Ista Zahn  wrote:


On Sun, Sep 23, 2018 at 1:46 PM Wensui Liu  wrote:


actually, by the parallel pvec, the user time is a lot shorter. or did
I somewhere miss your invaluable insight?


c1 <- 1:100
len <- length(c1)
rbenchmark::benchmark(log(c1[-1]/c1[-len]), replications = 100)

   test replications elapsed relative user.self sys.self
1 log(c1[-1]/c1[-len])  100   4.6171 4.4840.133
   user.child sys.child
1  0 0

rbenchmark::benchmark(pvec(1:(len - 1), mc.cores = 4, function(i) log(c1[i + 1] 
/ c1[i])), replications = 100)

test
1 pvec(1:(len - 1), mc.cores = 4, function(i) log(c1[i + 1]/c1[i]))
   replications elapsed relative user.self sys.self user.child sys.child
1  100   9.0791 2.5714.138  9.736 8.046


Your output is mangled in my email, but on my system your pvec
approach takes more than twice as long:

c1 <- 1:100
len <- length(c1)
library(parallel)
library(rbenchmark)

regular <- function() log(c1[-1]/c1[-len])
iterate.parallel <- function() {
   pvec(1:(len - 1), mc.cores = 4,
function(i) log(c1[i + 1] / c1[i]))
}

benchmark(regular(), iterate.parallel(),
   replications = 100,
   columns = c("test", "elapsed", "relative"))
## test elapsed relative
## 2 iterate.parallel()   7.5172.482
## 1  regular()   3.0281.000

Honestly, just use log(c1[-1]/c1[-len]). The code is simple and easy
to understand and it runs pretty fast. There is usually no reason to
make it more complicated.
--Ista


On Sun, Sep 23, 2018 at 12:33 PM Ista Zahn  wrote:


On Sun, Sep 23, 2018 at 10:09 AM Wensui Liu  wrote:


Why?


The operations required for this algorithm are vectorized, as are most
operations in R. There is no need to iterate through each element.
Using Vectorize to achieve the iteration is no better than using
*apply or a for-loop, and betrays the same basic lack of insight into
basic principles of programming in R.

And/or, if you want a more practical reason:


c1 <- 1:100
len <- 100
system.time( s1 <- log(c1[-1]/c1[-len]))

user  system elapsed
   0.031   0.004   0.035

system.time(s2 <- Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))

user  system elapsed
   1.258   0.022   1.282

Best,
Ista



On Sun, Sep 23, 2018 at 7:54 AM Ista Zahn  wrote:


On Sat, Sep 22, 2018 at 9:06 PM Wensui Liu  wrote:


or this one:

(Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))


Oh dear god no.



On Sat, Sep 22, 2018 at 4:16 PM rsherry8  wrote:



It is my impression that good R programmers make very little use of the
for statement. Please consider  the following
R statement:
  for( i in 1:(len-1) )  s[i] = log(c1[i+1]/c1[i], base = exp(1) )
One problem I have found with this statement is that s must exist before
the statement is run. Can i

Re: [R] For Loop

2018-09-23 Thread Sorkin, John
At the risk of asking something fundamental . . . .

does log(c1[-1]/c1[-len]

do the following


(1) use all elements of c and perform the calculation

(2) delete the first element of c and perform the calculation,

(2) delete the first two elements of c and perform the calculation,

 . . .

(n) use only the last element of c and perform the calculation.


Thank you,

John



John David Sorkin M.D., Ph.D.
Professor of Medicine
Chief, Biostatistics and Informatics
University of Maryland School of Medicine Division of Gerontology and Geriatric 
Medicine
Baltimore VA Medical Center
10 North Greene Street
GRECC (BT/18/GR)
Baltimore, MD 21201-1524
(Phone) 410-605-7119
(Fax) 410-605-7913 (Please call phone number above prior to faxing)




From: R-help  on behalf of Wensui Liu 

Sent: Sunday, September 23, 2018 2:26 PM
To: Ista Zahn
Cc: r-help@r-project.org
Subject: Re: [R] For Loop

CAUTION: This message originated from a non UMB, UMSOM, FPI, or UMMS email 
system. Whether the sender is known or not known, hover over any links before 
clicking and use caution opening attachments.



what you measures is the "elapsed" time in the default setting. you
might need to take a closer look at the beautiful benchmark() function
and see what time I am talking about.

I just provided tentative solution for the person asking for it  and
believe he has enough wisdom to decide what's best. why bother to
judge others subjectively?
On Sun, Sep 23, 2018 at 1:18 PM Ista Zahn  wrote:
>
> On Sun, Sep 23, 2018 at 1:46 PM Wensui Liu  wrote:
> >
> > actually, by the parallel pvec, the user time is a lot shorter. or did
> > I somewhere miss your invaluable insight?
> >
> > > c1 <- 1:100
> > > len <- length(c1)
> > > rbenchmark::benchmark(log(c1[-1]/c1[-len]), replications = 100)
> >   test replications elapsed relative user.self sys.self
> > 1 log(c1[-1]/c1[-len])  100   4.6171 4.4840.133
> >   user.child sys.child
> > 1  0 0
> > > rbenchmark::benchmark(pvec(1:(len - 1), mc.cores = 4, function(i) 
> > > log(c1[i + 1] / c1[i])), replications = 100)
> >test
> > 1 pvec(1:(len - 1), mc.cores = 4, function(i) log(c1[i + 1]/c1[i]))
> >   replications elapsed relative user.self sys.self user.child sys.child
> > 1  100   9.0791 2.5714.138  9.736 8.046
>
> Your output is mangled in my email, but on my system your pvec
> approach takes more than twice as long:
>
> c1 <- 1:100
> len <- length(c1)
> library(parallel)
> library(rbenchmark)
>
> regular <- function() log(c1[-1]/c1[-len])
> iterate.parallel <- function() {
>   pvec(1:(len - 1), mc.cores = 4,
>function(i) log(c1[i + 1] / c1[i]))
> }
>
> benchmark(regular(), iterate.parallel(),
>   replications = 100,
>   columns = c("test", "elapsed", "relative"))
> ## test elapsed relative
> ## 2 iterate.parallel()   7.5172.482
> ## 1  regular()   3.0281.000
>
> Honestly, just use log(c1[-1]/c1[-len]). The code is simple and easy
> to understand and it runs pretty fast. There is usually no reason to
> make it more complicated.
> --Ista
>
> > On Sun, Sep 23, 2018 at 12:33 PM Ista Zahn  wrote:
> > >
> > > On Sun, Sep 23, 2018 at 10:09 AM Wensui Liu  wrote:
> > > >
> > > > Why?
> > >
> > > The operations required for this algorithm are vectorized, as are most
> > > operations in R. There is no need to iterate through each element.
> > > Using Vectorize to achieve the iteration is no better than using
> > > *apply or a for-loop, and betrays the same basic lack of insight into
> > > basic principles of programming in R.
> > >
> > > And/or, if you want a more practical reason:
> > >
> > > > c1 <- 1:100
> > > > len <- 100
> > > > system.time( s1 <- log(c1[-1]/c1[-len]))
> > >user  system elapsed
> > >   0.031   0.004   0.035
> > > > system.time(s2 <- Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))
> > >user  system elapsed
> > >   1.258   0.022   1.282
> > >
> > > Best,
> > > Ista
> > >
> > > >
> > > > On Sun, Sep 23, 2018 at 7:54 AM Ista Zahn  wrote:
> > > >>
> > > >> On Sat, Sep 22, 2018 at 9:06 PM Wensui Liu  wrote:
> > > >> >
> > > >> > or this one:
> > > >> >
> > > >> > (Vectorize

Re: [R] For Loop

2018-09-23 Thread Wensui Liu
what you measures is the "elapsed" time in the default setting. you
might need to take a closer look at the beautiful benchmark() function
and see what time I am talking about.

I just provided tentative solution for the person asking for it  and
believe he has enough wisdom to decide what's best. why bother to
judge others subjectively?
On Sun, Sep 23, 2018 at 1:18 PM Ista Zahn  wrote:
>
> On Sun, Sep 23, 2018 at 1:46 PM Wensui Liu  wrote:
> >
> > actually, by the parallel pvec, the user time is a lot shorter. or did
> > I somewhere miss your invaluable insight?
> >
> > > c1 <- 1:100
> > > len <- length(c1)
> > > rbenchmark::benchmark(log(c1[-1]/c1[-len]), replications = 100)
> >   test replications elapsed relative user.self sys.self
> > 1 log(c1[-1]/c1[-len])  100   4.6171 4.4840.133
> >   user.child sys.child
> > 1  0 0
> > > rbenchmark::benchmark(pvec(1:(len - 1), mc.cores = 4, function(i) 
> > > log(c1[i + 1] / c1[i])), replications = 100)
> >test
> > 1 pvec(1:(len - 1), mc.cores = 4, function(i) log(c1[i + 1]/c1[i]))
> >   replications elapsed relative user.self sys.self user.child sys.child
> > 1  100   9.0791 2.5714.138  9.736 8.046
>
> Your output is mangled in my email, but on my system your pvec
> approach takes more than twice as long:
>
> c1 <- 1:100
> len <- length(c1)
> library(parallel)
> library(rbenchmark)
>
> regular <- function() log(c1[-1]/c1[-len])
> iterate.parallel <- function() {
>   pvec(1:(len - 1), mc.cores = 4,
>function(i) log(c1[i + 1] / c1[i]))
> }
>
> benchmark(regular(), iterate.parallel(),
>   replications = 100,
>   columns = c("test", "elapsed", "relative"))
> ## test elapsed relative
> ## 2 iterate.parallel()   7.5172.482
> ## 1  regular()   3.0281.000
>
> Honestly, just use log(c1[-1]/c1[-len]). The code is simple and easy
> to understand and it runs pretty fast. There is usually no reason to
> make it more complicated.
> --Ista
>
> > On Sun, Sep 23, 2018 at 12:33 PM Ista Zahn  wrote:
> > >
> > > On Sun, Sep 23, 2018 at 10:09 AM Wensui Liu  wrote:
> > > >
> > > > Why?
> > >
> > > The operations required for this algorithm are vectorized, as are most
> > > operations in R. There is no need to iterate through each element.
> > > Using Vectorize to achieve the iteration is no better than using
> > > *apply or a for-loop, and betrays the same basic lack of insight into
> > > basic principles of programming in R.
> > >
> > > And/or, if you want a more practical reason:
> > >
> > > > c1 <- 1:100
> > > > len <- 100
> > > > system.time( s1 <- log(c1[-1]/c1[-len]))
> > >user  system elapsed
> > >   0.031   0.004   0.035
> > > > system.time(s2 <- Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))
> > >user  system elapsed
> > >   1.258   0.022   1.282
> > >
> > > Best,
> > > Ista
> > >
> > > >
> > > > On Sun, Sep 23, 2018 at 7:54 AM Ista Zahn  wrote:
> > > >>
> > > >> On Sat, Sep 22, 2018 at 9:06 PM Wensui Liu  wrote:
> > > >> >
> > > >> > or this one:
> > > >> >
> > > >> > (Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))
> > > >>
> > > >> Oh dear god no.
> > > >>
> > > >> >
> > > >> > On Sat, Sep 22, 2018 at 4:16 PM rsherry8  
> > > >> > wrote:
> > > >> > >
> > > >> > >
> > > >> > > It is my impression that good R programmers make very little use 
> > > >> > > of the
> > > >> > > for statement. Please consider  the following
> > > >> > > R statement:
> > > >> > >  for( i in 1:(len-1) )  s[i] = log(c1[i+1]/c1[i], base = 
> > > >> > > exp(1) )
> > > >> > > One problem I have found with this statement is that s must exist 
> > > >> > > before
> > > >> > > the statement is run. Can it be written without using a for
> > > >> > > loop? Would that be better?
> > > >> > >
> > > >> > > Thanks,
> > > >> > > Bob
> > > >> > >
> > > >> > > __
> > > >> > > 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, 

Re: [R] For Loop

2018-09-23 Thread Ista Zahn
On Sun, Sep 23, 2018 at 1:46 PM Wensui Liu  wrote:
>
> actually, by the parallel pvec, the user time is a lot shorter. or did
> I somewhere miss your invaluable insight?
>
> > c1 <- 1:100
> > len <- length(c1)
> > rbenchmark::benchmark(log(c1[-1]/c1[-len]), replications = 100)
>   test replications elapsed relative user.self sys.self
> 1 log(c1[-1]/c1[-len])  100   4.6171 4.4840.133
>   user.child sys.child
> 1  0 0
> > rbenchmark::benchmark(pvec(1:(len - 1), mc.cores = 4, function(i) log(c1[i 
> > + 1] / c1[i])), replications = 100)
>test
> 1 pvec(1:(len - 1), mc.cores = 4, function(i) log(c1[i + 1]/c1[i]))
>   replications elapsed relative user.self sys.self user.child sys.child
> 1  100   9.0791 2.5714.138  9.736 8.046

Your output is mangled in my email, but on my system your pvec
approach takes more than twice as long:

c1 <- 1:100
len <- length(c1)
library(parallel)
library(rbenchmark)

regular <- function() log(c1[-1]/c1[-len])
iterate.parallel <- function() {
  pvec(1:(len - 1), mc.cores = 4,
   function(i) log(c1[i + 1] / c1[i]))
}

benchmark(regular(), iterate.parallel(),
  replications = 100,
  columns = c("test", "elapsed", "relative"))
## test elapsed relative
## 2 iterate.parallel()   7.5172.482
## 1  regular()   3.0281.000

Honestly, just use log(c1[-1]/c1[-len]). The code is simple and easy
to understand and it runs pretty fast. There is usually no reason to
make it more complicated.
--Ista

> On Sun, Sep 23, 2018 at 12:33 PM Ista Zahn  wrote:
> >
> > On Sun, Sep 23, 2018 at 10:09 AM Wensui Liu  wrote:
> > >
> > > Why?
> >
> > The operations required for this algorithm are vectorized, as are most
> > operations in R. There is no need to iterate through each element.
> > Using Vectorize to achieve the iteration is no better than using
> > *apply or a for-loop, and betrays the same basic lack of insight into
> > basic principles of programming in R.
> >
> > And/or, if you want a more practical reason:
> >
> > > c1 <- 1:100
> > > len <- 100
> > > system.time( s1 <- log(c1[-1]/c1[-len]))
> >user  system elapsed
> >   0.031   0.004   0.035
> > > system.time(s2 <- Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))
> >user  system elapsed
> >   1.258   0.022   1.282
> >
> > Best,
> > Ista
> >
> > >
> > > On Sun, Sep 23, 2018 at 7:54 AM Ista Zahn  wrote:
> > >>
> > >> On Sat, Sep 22, 2018 at 9:06 PM Wensui Liu  wrote:
> > >> >
> > >> > or this one:
> > >> >
> > >> > (Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))
> > >>
> > >> Oh dear god no.
> > >>
> > >> >
> > >> > On Sat, Sep 22, 2018 at 4:16 PM rsherry8  wrote:
> > >> > >
> > >> > >
> > >> > > It is my impression that good R programmers make very little use of 
> > >> > > the
> > >> > > for statement. Please consider  the following
> > >> > > R statement:
> > >> > >  for( i in 1:(len-1) )  s[i] = log(c1[i+1]/c1[i], base = 
> > >> > > exp(1) )
> > >> > > One problem I have found with this statement is that s must exist 
> > >> > > before
> > >> > > the statement is run. Can it be written without using a for
> > >> > > loop? Would that be better?
> > >> > >
> > >> > > Thanks,
> > >> > > Bob
> > >> > >
> > >> > > __
> > >> > > 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] For Loop

2018-09-23 Thread Wensui Liu
actually, by the parallel pvec, the user time is a lot shorter. or did
I somewhere miss your invaluable insight?

> c1 <- 1:100
> len <- length(c1)
> rbenchmark::benchmark(log(c1[-1]/c1[-len]), replications = 100)
  test replications elapsed relative user.self sys.self
1 log(c1[-1]/c1[-len])  100   4.6171 4.4840.133
  user.child sys.child
1  0 0
> rbenchmark::benchmark(pvec(1:(len - 1), mc.cores = 4, function(i) log(c1[i + 
> 1] / c1[i])), replications = 100)
   test
1 pvec(1:(len - 1), mc.cores = 4, function(i) log(c1[i + 1]/c1[i]))
  replications elapsed relative user.self sys.self user.child sys.child
1  100   9.0791 2.5714.138  9.736 8.046
On Sun, Sep 23, 2018 at 12:33 PM Ista Zahn  wrote:
>
> On Sun, Sep 23, 2018 at 10:09 AM Wensui Liu  wrote:
> >
> > Why?
>
> The operations required for this algorithm are vectorized, as are most
> operations in R. There is no need to iterate through each element.
> Using Vectorize to achieve the iteration is no better than using
> *apply or a for-loop, and betrays the same basic lack of insight into
> basic principles of programming in R.
>
> And/or, if you want a more practical reason:
>
> > c1 <- 1:100
> > len <- 100
> > system.time( s1 <- log(c1[-1]/c1[-len]))
>user  system elapsed
>   0.031   0.004   0.035
> > system.time(s2 <- Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))
>user  system elapsed
>   1.258   0.022   1.282
>
> Best,
> Ista
>
> >
> > On Sun, Sep 23, 2018 at 7:54 AM Ista Zahn  wrote:
> >>
> >> On Sat, Sep 22, 2018 at 9:06 PM Wensui Liu  wrote:
> >> >
> >> > or this one:
> >> >
> >> > (Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))
> >>
> >> Oh dear god no.
> >>
> >> >
> >> > On Sat, Sep 22, 2018 at 4:16 PM rsherry8  wrote:
> >> > >
> >> > >
> >> > > It is my impression that good R programmers make very little use of the
> >> > > for statement. Please consider  the following
> >> > > R statement:
> >> > >  for( i in 1:(len-1) )  s[i] = log(c1[i+1]/c1[i], base = 
> >> > > exp(1) )
> >> > > One problem I have found with this statement is that s must exist 
> >> > > before
> >> > > the statement is run. Can it be written without using a for
> >> > > loop? Would that be better?
> >> > >
> >> > > Thanks,
> >> > > Bob
> >> > >
> >> > > __
> >> > > 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] For Loop

2018-09-23 Thread Ista Zahn
On Sun, Sep 23, 2018 at 10:09 AM Wensui Liu  wrote:
>
> Why?

The operations required for this algorithm are vectorized, as are most
operations in R. There is no need to iterate through each element.
Using Vectorize to achieve the iteration is no better than using
*apply or a for-loop, and betrays the same basic lack of insight into
basic principles of programming in R.

And/or, if you want a more practical reason:

> c1 <- 1:100
> len <- 100
> system.time( s1 <- log(c1[-1]/c1[-len]))
   user  system elapsed
  0.031   0.004   0.035
> system.time(s2 <- Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))
   user  system elapsed
  1.258   0.022   1.282

Best,
Ista

>
> On Sun, Sep 23, 2018 at 7:54 AM Ista Zahn  wrote:
>>
>> On Sat, Sep 22, 2018 at 9:06 PM Wensui Liu  wrote:
>> >
>> > or this one:
>> >
>> > (Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))
>>
>> Oh dear god no.
>>
>> >
>> > On Sat, Sep 22, 2018 at 4:16 PM rsherry8  wrote:
>> > >
>> > >
>> > > It is my impression that good R programmers make very little use of the
>> > > for statement. Please consider  the following
>> > > R statement:
>> > >  for( i in 1:(len-1) )  s[i] = log(c1[i+1]/c1[i], base = exp(1) )
>> > > One problem I have found with this statement is that s must exist before
>> > > the statement is run. Can it be written without using a for
>> > > loop? Would that be better?
>> > >
>> > > Thanks,
>> > > Bob
>> > >
>> > > __
>> > > 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] For Loop

2018-09-23 Thread Ista Zahn
On Sat, Sep 22, 2018 at 9:06 PM Wensui Liu  wrote:
>
> or this one:
>
> (Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))

Oh dear god no.

>
> On Sat, Sep 22, 2018 at 4:16 PM rsherry8  wrote:
> >
> >
> > It is my impression that good R programmers make very little use of the
> > for statement. Please consider  the following
> > R statement:
> >  for( i in 1:(len-1) )  s[i] = log(c1[i+1]/c1[i], base = exp(1) )
> > One problem I have found with this statement is that s must exist before
> > the statement is run. Can it be written without using a for
> > loop? Would that be better?
> >
> > Thanks,
> > Bob
> >
> > __
> > 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] For Loop

2018-09-22 Thread Jeff Newmiller
I do use for loops a few times per month, but only wrapped around large chunks 
of vectorized calculations, not for this kind of use case. In those cases I 
also pre-allocate output vectors/lists (e.g. vector( "list", len )) to avoid 
memory thrashing as you grow lists or other vectors one element at a time (v <- 
c( v, new value ) is an inefficient trick). I also create variables to hold 
intermediate results that would yield the same answer each time before going 
into the loop (e.g. exp(1)).

As regards your toy example, I would use a one-liner:

s <- diff( log( c1 ) )

which avoids executing exp(1) at all, much less every time through the loop, 
and it uses vectorized incremental subtraction rather than division (laws of 
logarithms from algebra). The default base for the log function is e, so it is 
unnecessary to specify it. Note that your loop calculates logs involving all 
but the first and last elements of c1 twice... once when indexing for i+1, and 
again in the next iteration of the loop it is accessed as index i.

You would be surprised how many iterative algorithms can be accomplished with 
cumsum and diff. Bill Dunlap has demonstrated examples quite a few times in the 
mailing list archives if you have time  to search.

On September 22, 2018 2:16:27 PM PDT, rsherry8  wrote:
>
>It is my impression that good R programmers make very little use of the
>
>for statement. Please consider  the following
>R statement:
>   for( i in 1:(len-1) )  s[i] = log(c1[i+1]/c1[i], base = exp(1) )
>One problem I have found with this statement is that s must exist
>before 
>the statement is run. Can it be written without using a for
>loop? Would that be better?
>
>Thanks,
>Bob
>
>__
>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.

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

__
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] For Loop

2018-09-22 Thread Wensui Liu
or this one:

(Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))

On Sat, Sep 22, 2018 at 4:16 PM rsherry8  wrote:
>
>
> It is my impression that good R programmers make very little use of the
> for statement. Please consider  the following
> R statement:
>  for( i in 1:(len-1) )  s[i] = log(c1[i+1]/c1[i], base = exp(1) )
> One problem I have found with this statement is that s must exist before
> the statement is run. Can it be written without using a for
> loop? Would that be better?
>
> Thanks,
> Bob
>
> __
> 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] For Loop

2018-09-22 Thread Wensui Liu
another version just for fun

s <- parallel::pvec(1:len, function(i) log(c1[i + 1] / c1[i]))
On Sat, Sep 22, 2018 at 4:16 PM rsherry8  wrote:
>
>
> It is my impression that good R programmers make very little use of the
> for statement. Please consider  the following
> R statement:
>  for( i in 1:(len-1) )  s[i] = log(c1[i+1]/c1[i], base = exp(1) )
> One problem I have found with this statement is that s must exist before
> the statement is run. Can it be written without using a for
> loop? Would that be better?
>
> Thanks,
> Bob
>
> __
> 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] For Loop

2018-09-22 Thread Richard M. Heiberger
c1 <- 1:100
len <- 100
system.time(
s1 <- log(c1[-1]/c1[-len])
)
s <- c1[-len]
system.time(
for (i in 1:(len-1)) s[i] <- log(c1[i+1]/c1[i])
)
all.equal(s,s1)


>
> c1 <- 1:100
> len <- 100
> system.time(
+ s1 <- log(c1[-1]/c1[-len])
+ )
   user  system elapsed
  0.032   0.005   0.037
> s <- c1[-len]
> system.time(
+ for (i in 1:(len-1)) s[i] <- log(c1[i+1]/c1[i])
+ )
   user  system elapsed
  0.226   0.002   0.232
> all.equal(s,s1)
[1] TRUE
>

much faster, and much easier to understand when vectorized

On Sat, Sep 22, 2018 at 5:16 PM, rsherry8  wrote:
>
> It is my impression that good R programmers make very little use of the for
> statement. Please consider  the following
> R statement:
> for( i in 1:(len-1) )  s[i] = log(c1[i+1]/c1[i], base = exp(1) )
> One problem I have found with this statement is that s must exist before the
> statement is run. Can it be written without using a for
> loop? Would that be better?
>
> Thanks,
> Bob
>
> __
> 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] For Loop

2018-09-22 Thread Bert Gunter
Bob:

Please, please spend some time with an R tutorial or two before you post
here. This list can help, but I think we assume that you have already made
an effort to learn basic R on your own. Your question is about as basic as
it gets, so it appears to me that you have not done this. There are many
many R tutorials out there. Some suggestions, by no means comprehensive,
can be found here:
https://www.rstudio.com/online-learning/#r-programming

Others will no doubt respond, but you can answer it yourself after only a
few minutes with most R tutorials.

Cheers,
Bert




On Sat, Sep 22, 2018 at 2:16 PM rsherry8  wrote:

>
> It is my impression that good R programmers make very little use of the
> for statement. Please consider  the following
> R statement:
>  for( i in 1:(len-1) )  s[i] = log(c1[i+1]/c1[i], base = exp(1) )
> One problem I have found with this statement is that s must exist before
> the statement is run. Can it be written without using a for
> loop? Would that be better?
>
> Thanks,
> Bob
>
> __
> 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] For Loop

2018-09-22 Thread rsherry8



It is my impression that good R programmers make very little use of the 
for statement. Please consider  the following

R statement:
for( i in 1:(len-1) )  s[i] = log(c1[i+1]/c1[i], base = exp(1) )
One problem I have found with this statement is that s must exist before 
the statement is run. Can it be written without using a for

loop? Would that be better?

Thanks,
Bob

__
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] For loop with multiple iteration indexes

2018-09-11 Thread David L Carlson
Just for fun, there are ways to do this in R without an explicit loop:

> set.seed(42)
> dat <- matrix(rnorm(10*5), 10, 5)
> x <- sample(1:5)
> y <- sample(1:5)
> diag(cor(dat[, x], dat[, y]))
[1] -0.69156568 -0.06002371 -0.37492894  0.46477742 -0.37972866

You can use as.list() to convert the vector to a list.

> i <- seq_len(length(x))
> sapply(i, function(j) cor(dat[, x[j]], dat[, y[j]]))
[1] -0.69156568 -0.06002371 -0.37492894  0.46477742 -0.37972866
> xy <- cbind(x, y)
> sapply(i, function(j) cor(dat[, xy[j, ]])[1, 2])
[1] -0.69156568 -0.06002371 -0.37492894  0.46477742 -0.37972866

Change sapply() to lapply() to get list output.


David L Carlson
Department of Anthropology
Texas A University
College Station, TX 77843-4352

-Original Message-
From: R-help  On Behalf Of David Disabato
Sent: Monday, September 10, 2018 8:33 PM
To: r-help@r-project.org
Subject: Re: [R] For loop with multiple iteration indexes

Thank you everyone. After thinking about each response, I realized a fairly 
simple solution is available (obviously, other suggested approaches work as
well):

stopifnot(length(x) == length(y); stopifnot(length(x) > 0) r <- list() for (i 
in 1:length(x) ) {
   r[[i]] <- cor(x = dat[, x[i] ], y = dat[, y[i] ]) }
print(r)

On Mon, Sep 10, 2018 at 11:30 AM Berry, Charles  wrote:

> I have a sense of deja vu:
>
> https://www.mail-archive.com/r-help@r-project.org/msg250494.html
>
> There is some good advice there.
>
> > On Sep 9, 2018, at 3:49 PM, David Disabato  wrote:
> >
> > Hi R-help,
> >
> > I am trying to create a for loop with multiple iteration indexes. I 
> > don't want to use two different for loops nested together because I 
> > don't need the full matrix of the two indexes, just the diagonal 
> > elements (e.g.,
> i[1]
> > & j[1] and i[2] & j[2], but not i[1] & j[2]). Is there a way to 
> > specify both i and j in a single for loop? Here is a simplified 
> > example of pseudo-code where x and y are equally sized character 
> > vectors with column names and dat is their dataframe (obviously this 
> > code doesn't run in R,
> but
> > hopefully you perceive my goal):
> >
> > r <- list()
> > n <- 0
> > for (i in x; j in y) {
> >   n <- n + 1
> >   r[[n]] <- cor(x = dat[, i], y = dat[, j]) }
> > print(r)
> >
> > I realize there are other solutions to this particular correlation
> example,
> > but my actual problem is much more complicated, so I am hoping for a 
> > solution that generalizes across any code within the for loop.
>
> A more aRtful way (than a for loop) to approach this is with mapply:
>
>
> i <- head(colnames(mtcars))
> j <- tail(colnames(mtcars))
>
> r <- mapply(function(i, j, dat) cor( x = dat[, i], y = dat[, j]),
>i=i , j=j , MoreArgs = list( dat = mtcars),
>SIMPLIFY = FALSE, USE.NAMES = FALSE)
>
>
> and if you want, maybe USE.NAMES = paste(i, j, sep="_")
>
> Chuck
>
>

--
David J. Disabato, M.A.
Clinical Psychology Doctoral Student
George Mason University
ddisa...@gmu.edu

Email is not a secure form of communication as information and confidentiality 
cannot be guaranteed. Information provided in an email is not intended to be a 
professional service. In the case of a crisis or emergency situation, call 911.

[[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] For loop with multiple iteration indexes

2018-09-10 Thread David Disabato
Thank you everyone. After thinking about each response, I realized a fairly
simple solution is available (obviously, other suggested approaches work as
well):

stopifnot(length(x) == length(y); stopifnot(length(x) > 0)
r <- list()
for (i in 1:length(x) ) {
   r[[i]] <- cor(x = dat[, x[i] ], y = dat[, y[i] ])
}
print(r)

On Mon, Sep 10, 2018 at 11:30 AM Berry, Charles  wrote:

> I have a sense of deja vu:
>
> https://www.mail-archive.com/r-help@r-project.org/msg250494.html
>
> There is some good advice there.
>
> > On Sep 9, 2018, at 3:49 PM, David Disabato  wrote:
> >
> > Hi R-help,
> >
> > I am trying to create a for loop with multiple iteration indexes. I don't
> > want to use two different for loops nested together because I don't need
> > the full matrix of the two indexes, just the diagonal elements (e.g.,
> i[1]
> > & j[1] and i[2] & j[2], but not i[1] & j[2]). Is there a way to specify
> > both i and j in a single for loop? Here is a simplified example of
> > pseudo-code where x and y are equally sized character vectors with column
> > names and dat is their dataframe (obviously this code doesn't run in R,
> but
> > hopefully you perceive my goal):
> >
> > r <- list()
> > n <- 0
> > for (i in x; j in y) {
> >   n <- n + 1
> >   r[[n]] <- cor(x = dat[, i], y = dat[, j])
> > }
> > print(r)
> >
> > I realize there are other solutions to this particular correlation
> example,
> > but my actual problem is much more complicated, so I am hoping for a
> > solution that generalizes across any code within the for loop.
>
> A more aRtful way (than a for loop) to approach this is with mapply:
>
>
> i <- head(colnames(mtcars))
> j <- tail(colnames(mtcars))
>
> r <- mapply(function(i, j, dat) cor( x = dat[, i], y = dat[, j]),
>i=i , j=j , MoreArgs = list( dat = mtcars),
>SIMPLIFY = FALSE, USE.NAMES = FALSE)
>
>
> and if you want, maybe USE.NAMES = paste(i, j, sep="_")
>
> Chuck
>
>

-- 
David J. Disabato, M.A.
Clinical Psychology Doctoral Student
George Mason University
ddisa...@gmu.edu

Email is not a secure form of communication as information and
confidentiality cannot be guaranteed. Information provided in an email is
not intended to be a professional service. In the case of a crisis or
emergency situation, call 911.

[[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] For loop with multiple iteration indexes

2018-09-10 Thread Berry, Charles
I have a sense of deja vu:

https://www.mail-archive.com/r-help@r-project.org/msg250494.html

There is some good advice there.

> On Sep 9, 2018, at 3:49 PM, David Disabato  wrote:
> 
> Hi R-help,
> 
> I am trying to create a for loop with multiple iteration indexes. I don't
> want to use two different for loops nested together because I don't need
> the full matrix of the two indexes, just the diagonal elements (e.g., i[1]
> & j[1] and i[2] & j[2], but not i[1] & j[2]). Is there a way to specify
> both i and j in a single for loop? Here is a simplified example of
> pseudo-code where x and y are equally sized character vectors with column
> names and dat is their dataframe (obviously this code doesn't run in R, but
> hopefully you perceive my goal):
> 
> r <- list()
> n <- 0
> for (i in x; j in y) {
>   n <- n + 1
>   r[[n]] <- cor(x = dat[, i], y = dat[, j])
> }
> print(r)
> 
> I realize there are other solutions to this particular correlation example,
> but my actual problem is much more complicated, so I am hoping for a
> solution that generalizes across any code within the for loop.

A more aRtful way (than a for loop) to approach this is with mapply:


i <- head(colnames(mtcars))
j <- tail(colnames(mtcars))

r <- mapply(function(i, j, dat) cor( x = dat[, i], y = dat[, j]),
   i=i , j=j , MoreArgs = list( dat = mtcars), 
   SIMPLIFY = FALSE, USE.NAMES = FALSE)


and if you want, maybe USE.NAMES = paste(i, j, sep="_")

Chuck

__
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] For loop with multiple iteration indexes

2018-09-10 Thread Albrecht Kauffmann
Hi,

this simple example is very similarly, and it works in R:

r <- list()
n <- 0
x <- c("a","b","c")#x,y: Data from a dataframe
y <- c("A","B","C")
for (k in 1:3) {
n <- n+1
r[[n]] <- paste0(x[k],y[k])#or any other function using x[k] and y[k] as 
arguments
}
print(r)

Is it this what you meant?

Best,
Albrecht

-- 
  Albrecht Kauffmann
  alkau...@fastmail.fm

Am Mo, 10. Sep 2018, um 00:49, schrieb David Disabato:
> Hi R-help,
> 
> I am trying to create a for loop with multiple iteration indexes. I don't
> want to use two different for loops nested together because I don't need
> the full matrix of the two indexes, just the diagonal elements (e.g., i[1]
> & j[1] and i[2] & j[2], but not i[1] & j[2]). Is there a way to specify
> both i and j in a single for loop? Here is a simplified example of
> pseudo-code where x and y are equally sized character vectors with column
> names and dat is their dataframe (obviously this code doesn't run in R, but
> hopefully you perceive my goal):
> 
> r <- list()
> n <- 0
> for (i in x; j in y) {
>n <- n + 1
>r[[n]] <- cor(x = dat[, i], y = dat[, j])
> }
> print(r)
> 
> I realize there are other solutions to this particular correlation example,
> but my actual problem is much more complicated, so I am hoping for a
> solution that generalizes across any code within the for loop.
> 
> -- 
> David J. Disabato, M.A.
> Clinical Psychology Doctoral Student
> George Mason University
> ddisa...@gmu.edu
> 
> Email is not a secure form of communication as information and
> confidentiality cannot be guaranteed. Information provided in an email is
> not intended to be a professional service. In the case of a crisis or
> emergency situation, call 911.
> 
>   [[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] For loop with multiple iteration indexes

2018-09-09 Thread Jim Lemon
Hi David,
If you mean that you have two data frames named x and y and want the
correlations between the columns that would be on the diagonal of a
correlation matrix:

r<-list()
for(i in 1:n) r[[i]]<-cor(x[,i],y[,i])

If I'm wrong, let me know.

Jim

On Mon, Sep 10, 2018 at 3:06 PM David Disabato  wrote:
>
> Hi R-help,
>
> I am trying to create a for loop with multiple iteration indexes. I don't
> want to use two different for loops nested together because I don't need
> the full matrix of the two indexes, just the diagonal elements (e.g., i[1]
> & j[1] and i[2] & j[2], but not i[1] & j[2]). Is there a way to specify
> both i and j in a single for loop? Here is a simplified example of
> pseudo-code where x and y are equally sized character vectors with column
> names and dat is their dataframe (obviously this code doesn't run in R, but
> hopefully you perceive my goal):
>
> r <- list()
> n <- 0
> for (i in x; j in y) {
>n <- n + 1
>r[[n]] <- cor(x = dat[, i], y = dat[, j])
> }
> print(r)
>
> I realize there are other solutions to this particular correlation example,
> but my actual problem is much more complicated, so I am hoping for a
> solution that generalizes across any code within the for loop.
>
> --
> David J. Disabato, M.A.
> Clinical Psychology Doctoral Student
> George Mason University
> ddisa...@gmu.edu
>
> Email is not a secure form of communication as information and
> confidentiality cannot be guaranteed. Information provided in an email is
> not intended to be a professional service. In the case of a crisis or
> emergency situation, call 911.
>
> [[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.


[R] For loop with multiple iteration indexes

2018-09-09 Thread David Disabato
Hi R-help,

I am trying to create a for loop with multiple iteration indexes. I don't
want to use two different for loops nested together because I don't need
the full matrix of the two indexes, just the diagonal elements (e.g., i[1]
& j[1] and i[2] & j[2], but not i[1] & j[2]). Is there a way to specify
both i and j in a single for loop? Here is a simplified example of
pseudo-code where x and y are equally sized character vectors with column
names and dat is their dataframe (obviously this code doesn't run in R, but
hopefully you perceive my goal):

r <- list()
n <- 0
for (i in x; j in y) {
   n <- n + 1
   r[[n]] <- cor(x = dat[, i], y = dat[, j])
}
print(r)

I realize there are other solutions to this particular correlation example,
but my actual problem is much more complicated, so I am hoping for a
solution that generalizes across any code within the for loop.

-- 
David J. Disabato, M.A.
Clinical Psychology Doctoral Student
George Mason University
ddisa...@gmu.edu

Email is not a secure form of communication as information and
confidentiality cannot be guaranteed. Information provided in an email is
not intended to be a professional service. In the case of a crisis or
emergency situation, call 911.

[[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] loop para repetir valores de un vector

2018-07-12 Thread Víctor Granda García
Hola a todos,

No es necesario ningún bucle for ni nada por el estilo. La función rep ya
contempla esa opción:

alt <- rep(altitud$altitud, each = 1247)

hace exactamente lo que quieres Priscila.

Espero que te sirva, un saludo!!

On Thu, 12 Jul 2018 at 16:59 Juan Abasolo  wrote:

> Más fácil:
>
> altitud=read.csv("./altitud44.csv")
>
> y <- c() # Vacio
> for(i in altitud$altitud){
> print(i)
> x<- rep(i,1247)
> y <- c(y,x)
> }
>
>
> 2018-07-12 16:48 GMT+02:00 Juan Abasolo :
>
> > Hola, Priscila;
> >
> > A mí me parece que así me salió:
> >
> > altitud <- read.csv("./altitud44.csv")
> >
> > y <- list()
> > for(i in altitud$altitud){
> > print(i)
> > x<- rep(i,1247)
> > y[[length(y)+1]] <- x
> > }
> > z <- c()
> > for(i in 1:length(y)){
> > print(i)
> > z <- c(z,y[[i]])
> > }
> >
> > Es código muy primitivo y desprolijo de alumno, pero si te sirve...
> >
> > Suerte
> >
> > 2018-07-12 15:42 GMT+02:00 Priscila Ana Powell <
> priscilaapow...@gmail.com>
> > :
> >
> >> Hola a todos!
> >>
> >> Estoy intentando crear un vector (alt) a partir de la repetición de
> >> valores provenientes de otro vector (altitud).
> >> A cada valor de altitud lo quiero repetir 1247 veces, y de ahi continuar
> >> con el siguiente valor de altitud.
> >>
> >> Probé varias cosas, pero esto me pareció lo más coherente:
> >>
> >> altitud=read.csv("C:/Users/IER/Dropbox/Pasantia
> >> Castelar/YungasLigustroTS/altitud44.csv")
> >>
> >> alt=numeric (44*1247) #lo especifico asi porque tal vez tenga que
> cambiar
> >> las dimensiones segun otros valores)
> >>
> >> for (i in 1:44){
> >>   alt[((i-1)*1247+1):(i*1247)]<-for (ii in altitud) {rep (ii, 1247)
> >> }
> >> }
> >>
> >> Adjunto el vector altitud.
> >>
> >> desde ya, muchas gracias
> >>
> >> saludos!
> >>
> >> Priscila
> >> --
> >> Dra. Priscila Ana Powell
> >> Instituto de Ecología Regional-CONICET
> >> Cátedra de Ecología General-Facultad de Ciencias Naturales e Instituto
> >> Miguel Lillo
> >> Universidad Nacional de Tucumán
> >> Argentina
> >>
> >> ___
> >> R-help-es mailing list
> >> R-help-es@r-project.org
> >> https://stat.ethz.ch/mailman/listinfo/r-help-es
> >>
> >>
> >
> >
> > --
> > Juan Abasolo
> >
> > Hizkuntzaren eta Literaturaren Didaktika Saila
> > Bilboko Hezkuntza Fakultatea
> > Euskal Herriko Unibertsitatea
> > UPV/EHU
> >
> > Sarriena auzoa z/g
> > 48940 Leioa
> > Bizkaia
> >
>
>
>
> --
> Juan Abasolo
>
> Hizkuntzaren eta Literaturaren Didaktika Saila
> Bilboko Hezkuntza Fakultatea
> Euskal Herriko Unibertsitatea
> UPV/EHU
>
> Sarriena auzoa z/g
> 48940 Leioa
> Bizkaia
>
> [[alternative HTML version deleted]]
>
> ___
> R-help-es mailing list
> R-help-es@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-help-es
>
-- 
*Víctor Granda García*
Data Technician


v.gra...@creaf.uab.cat
Tel. +34 93 581 33 53


Campus UAB. Edifici C. 08193 Bellaterra (Barcelona) | *www.creaf.cat*


Abans d'imprimir aquest missatge electrònic penseu en el medi ambient.

[[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] loop para repetir valores de un vector

2018-07-12 Thread Juan Abasolo
Más fácil:

altitud=read.csv("./altitud44.csv")

y <- c() # Vacio
for(i in altitud$altitud){
print(i)
x<- rep(i,1247)
y <- c(y,x)
}


2018-07-12 16:48 GMT+02:00 Juan Abasolo :

> Hola, Priscila;
>
> A mí me parece que así me salió:
>
> altitud <- read.csv("./altitud44.csv")
>
> y <- list()
> for(i in altitud$altitud){
> print(i)
> x<- rep(i,1247)
> y[[length(y)+1]] <- x
> }
> z <- c()
> for(i in 1:length(y)){
> print(i)
> z <- c(z,y[[i]])
> }
>
> Es código muy primitivo y desprolijo de alumno, pero si te sirve...
>
> Suerte
>
> 2018-07-12 15:42 GMT+02:00 Priscila Ana Powell 
> :
>
>> Hola a todos!
>>
>> Estoy intentando crear un vector (alt) a partir de la repetición de
>> valores provenientes de otro vector (altitud).
>> A cada valor de altitud lo quiero repetir 1247 veces, y de ahi continuar
>> con el siguiente valor de altitud.
>>
>> Probé varias cosas, pero esto me pareció lo más coherente:
>>
>> altitud=read.csv("C:/Users/IER/Dropbox/Pasantia
>> Castelar/YungasLigustroTS/altitud44.csv")
>>
>> alt=numeric (44*1247) #lo especifico asi porque tal vez tenga que cambiar
>> las dimensiones segun otros valores)
>>
>> for (i in 1:44){
>>   alt[((i-1)*1247+1):(i*1247)]<-for (ii in altitud) {rep (ii, 1247)
>> }
>> }
>>
>> Adjunto el vector altitud.
>>
>> desde ya, muchas gracias
>>
>> saludos!
>>
>> Priscila
>> --
>> Dra. Priscila Ana Powell
>> Instituto de Ecología Regional-CONICET
>> Cátedra de Ecología General-Facultad de Ciencias Naturales e Instituto
>> Miguel Lillo
>> Universidad Nacional de Tucumán
>> Argentina
>>
>> ___
>> R-help-es mailing list
>> R-help-es@r-project.org
>> https://stat.ethz.ch/mailman/listinfo/r-help-es
>>
>>
>
>
> --
> Juan Abasolo
>
> Hizkuntzaren eta Literaturaren Didaktika Saila
> Bilboko Hezkuntza Fakultatea
> Euskal Herriko Unibertsitatea
> UPV/EHU
>
> Sarriena auzoa z/g
> 48940 Leioa
> Bizkaia
>



-- 
Juan Abasolo

Hizkuntzaren eta Literaturaren Didaktika Saila
Bilboko Hezkuntza Fakultatea
Euskal Herriko Unibertsitatea
UPV/EHU

Sarriena auzoa z/g
48940 Leioa
Bizkaia

[[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] loop para repetir valores de un vector

2018-07-12 Thread Juan Abasolo
Hola, Priscila;

A mí me parece que así me salió:

altitud <- read.csv("./altitud44.csv")

y <- list()
for(i in altitud$altitud){
print(i)
x<- rep(i,1247)
y[[length(y)+1]] <- x
}
z <- c()
for(i in 1:length(y)){
print(i)
z <- c(z,y[[i]])
}

Es código muy primitivo y desprolijo de alumno, pero si te sirve...

Suerte

2018-07-12 15:42 GMT+02:00 Priscila Ana Powell :

> Hola a todos!
>
> Estoy intentando crear un vector (alt) a partir de la repetición de
> valores provenientes de otro vector (altitud).
> A cada valor de altitud lo quiero repetir 1247 veces, y de ahi continuar
> con el siguiente valor de altitud.
>
> Probé varias cosas, pero esto me pareció lo más coherente:
>
> altitud=read.csv("C:/Users/IER/Dropbox/Pasantia Castelar/YungasLigustroTS/
> altitud44.csv")
>
> alt=numeric (44*1247) #lo especifico asi porque tal vez tenga que cambiar
> las dimensiones segun otros valores)
>
> for (i in 1:44){
>   alt[((i-1)*1247+1):(i*1247)]<-for (ii in altitud) {rep (ii, 1247)
> }
> }
>
> Adjunto el vector altitud.
>
> desde ya, muchas gracias
>
> saludos!
>
> Priscila
> --
> Dra. Priscila Ana Powell
> Instituto de Ecología Regional-CONICET
> Cátedra de Ecología General-Facultad de Ciencias Naturales e Instituto
> Miguel Lillo
> Universidad Nacional de Tucumán
> Argentina
>
> ___
> R-help-es mailing list
> R-help-es@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-help-es
>
>


-- 
Juan Abasolo

Hizkuntzaren eta Literaturaren Didaktika Saila
Bilboko Hezkuntza Fakultatea
Euskal Herriko Unibertsitatea
UPV/EHU

Sarriena auzoa z/g
48940 Leioa
Bizkaia

[[alternative HTML version deleted]]

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


[R-es] loop para repetir valores de un vector

2018-07-12 Thread Priscila Ana Powell
Hola a todos!

Estoy intentando crear un vector (alt) a partir de la repetición de valores
provenientes de otro vector (altitud).
A cada valor de altitud lo quiero repetir 1247 veces, y de ahi continuar
con el siguiente valor de altitud.

Probé varias cosas, pero esto me pareció lo más coherente:

altitud=read.csv("C:/Users/IER/Dropbox/Pasantia
Castelar/YungasLigustroTS/altitud44.csv")

alt=numeric (44*1247) #lo especifico asi porque tal vez tenga que cambiar
las dimensiones segun otros valores)

for (i in 1:44){
  alt[((i-1)*1247+1):(i*1247)]<-for (ii in altitud) {rep (ii, 1247)
}
}

Adjunto el vector altitud.

desde ya, muchas gracias

saludos!

Priscila
-- 
Dra. Priscila Ana Powell
Instituto de Ecología Regional-CONICET
Cátedra de Ecología General-Facultad de Ciencias Naturales e Instituto
Miguel Lillo
Universidad Nacional de Tucumán
Argentina


altitud44.csv
Description: MS-Excel spreadsheet
___
R-help-es mailing list
R-help-es@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-help-es


Re: [R-es] loop con matriz que cambia de nombre

2018-06-25 Thread Javier Marcuzzi
Estimado Manuel Mendoza

Entonces el problema es simple, primero cree una estructura para almacenar
los datos mediante repeticiones, algún paste() en el medio, de tal forma
que quede como usted desea, para esto comience de cero, no mire el código
con errores para no confundirse, mire algún ejemplo como los que hay en
http://www.datasciencemadesimple.com/repeat-and-replicate-function-in-r/ ,
cree el andamiaje, con algo muy simple como almacenar tablas de multiplicar
en data.frames, luego reemplaza esa función por la función que busca los
datos en la base de datos.

Es la forma que yo tengo, aunque por ahí aparecen errores, por ejemplo
ahora se me cae el código luego de procesar 10 horas, y me pregunto que
pasó para que luego de miles de cosas bien aparezca algo que rompe el
proceso, y bueno, es así, la importación de datos tiene esos problemas.

Javier Rubén Marcuzzi

El lun., 25 jun. 2018 a las 7:03, Marcelino de la Cruz Rot (<
marcelino.delac...@urjc.es>) escribió:

> El 25/06/2018 a las 11:23, Manuel Mendoza escribió:
> > Gracias Carlos, eso lo sé. El problema, probablemente una chorrada, es
> > que para cambiarle el nombre a las variables (de acuerdo a un patrón,
> > si, que incluye el nº de la iteración), debo indicar el nombre de la
> > df, pero éste no es siempre el mismo. Puedo darle un nombre fijo a la
> > df, ponerle el nombre a las variables, y al final del loop cambiarle
> > el nombre a la df, pero tampoco sé cómo ponerle un nombre nuevo que
> > incluye paste + el nº de iteración de los dos loops anidados. Sé como
> > crear ese nombre, con paste, pero no cómo ponérselo. Al decirlo así
> > parece una tontería, y a lo mejor lo es, pero me tiré un rato
> > intentándolo y no pude. Por eso acudí a vosotros.
>
> ¿Con assign(), como sugería Jesús?
>
> Saludos,
>
> Marcelino
>
>
>
>
>
>
>
> > Manuel
> >
> >
> > Quoting Carlos Ortega :
> >
> >> Hola,
> >>
> >> En cada iteración de tu bucle, puedes:
> >>
> >>- Cambiar la matriz a data.frame.
> >>- Nombrar las columnas incluyendo si quieres el número de la
> >> iteración
> >>del bucle (tu "i").
> >>   - Esto lo puedes hacer utiizando la función "paste()".
> >>   - No sé si los nombres de las variables, en cada iteración han de
> >>   seguir algún patrón.
> >>
> >>
> >> Saludos,
> >> Carlos Ortega
> >> www.qualityexcellence.es
> >>
> >> El 22 de junio de 2018, 19:53, Manuel Mendoza 
> >> escribió:
> >>
> >>>
> >>> Funciona, me crea una matriz en cada iteración, con un nombre que
> >>> incluye
> >>> el nº de la iteración. Me surge ahora el problema de que, dentro del
> >>> mismo
> >>> bucle la quiero convertir en df y ponerle nombre a las columnas, y
> >>> como el
> >>> nombre de la matriz es distinto cada vez, no sé cómo hacerlo.
> >>> Supongo que
> >>> se hará todo al crearla, pero no sé cómo.
> >>>
> >>> Un problema adicional es que las variables (columnas) también han de
> >>> llevar la "i" incluida en el nombre, porque al final se fusionan
> >>> todas las
> >>> dfs y no se puede repetir el nombre de las variables.
> >>>
> >>> Gracias una vez más.
> >>>
> >>>
> >>>
> >>>
> >>> Quoting Jesús Para Fernández :
> >>>
> >>> Con assing y un paste0
> >>>>
> >>>> Mete dentro del bucle esto
> >>>>
> >>>> for(i in 1:7){
> >>>> assign(paste0('matriz',i),matrix(0,ncol=5,nrow=3))
> >>>>
> >>>> }
> >>>>
> >>>> Con eso generarias 7 matrices de 5x3, llamadas matriz1, matriz2,...
> >>>>
> >>>> Obtener Outlook para Android<https://aka.ms/ghei36>
> >>>>
> >>>> 
> >>>> From: R-help-es  on behalf of Manuel
> >>>> Mendoza 
> >>>> Sent: Friday, June 22, 2018 10:15:55 AM
> >>>> To: r-help-es@r-project.org
> >>>> Subject: [R-es] loop con matriz que cambia de nombre
> >>>>
> >>>>
> >>>> Buenos días. Quiero hacer un for (j), anidado en otro for (i). En el
> >>>> 2º for, en cada iteración ha de crear una matriz vacía: mat <-
> >>>> matrix(nrow=nrow(data),ncol=19) pero llamándola de forma distinta cada
> >>>> vez. El nombre ha de ser: paste(

Re: [R-es] loop con matriz que cambia de nombre

2018-06-25 Thread Marcelino de la Cruz Rot

El 25/06/2018 a las 11:23, Manuel Mendoza escribió:
Gracias Carlos, eso lo sé. El problema, probablemente una chorrada, es 
que para cambiarle el nombre a las variables (de acuerdo a un patrón, 
si, que incluye el nº de la iteración), debo indicar el nombre de la 
df, pero éste no es siempre el mismo. Puedo darle un nombre fijo a la 
df, ponerle el nombre a las variables, y al final del loop cambiarle 
el nombre a la df, pero tampoco sé cómo ponerle un nombre nuevo que 
incluye paste + el nº de iteración de los dos loops anidados. Sé como 
crear ese nombre, con paste, pero no cómo ponérselo. Al decirlo así 
parece una tontería, y a lo mejor lo es, pero me tiré un rato 
intentándolo y no pude. Por eso acudí a vosotros.


¿Con assign(), como sugería Jesús?

Saludos,

Marcelino








Manuel


Quoting Carlos Ortega :


Hola,

En cada iteración de tu bucle, puedes:

   - Cambiar la matriz a data.frame.
   - Nombrar las columnas incluyendo si quieres el número de la 
iteración

   del bucle (tu "i").
  - Esto lo puedes hacer utiizando la función "paste()".
  - No sé si los nombres de las variables, en cada iteración han de
  seguir algún patrón.


Saludos,
Carlos Ortega
www.qualityexcellence.es

El 22 de junio de 2018, 19:53, Manuel Mendoza 
escribió:



Funciona, me crea una matriz en cada iteración, con un nombre que 
incluye
el nº de la iteración. Me surge ahora el problema de que, dentro del 
mismo
bucle la quiero convertir en df y ponerle nombre a las columnas, y 
como el
nombre de la matriz es distinto cada vez, no sé cómo hacerlo. 
Supongo que

se hará todo al crearla, pero no sé cómo.

Un problema adicional es que las variables (columnas) también han de
llevar la "i" incluida en el nombre, porque al final se fusionan 
todas las

dfs y no se puede repetir el nombre de las variables.

Gracias una vez más.




Quoting Jesús Para Fernández :

Con assing y un paste0


Mete dentro del bucle esto

for(i in 1:7){
assign(paste0('matriz',i),matrix(0,ncol=5,nrow=3))

}

Con eso generarias 7 matrices de 5x3, llamadas matriz1, matriz2,...

Obtener Outlook para Android<https://aka.ms/ghei36>


From: R-help-es  on behalf of Manuel
Mendoza 
Sent: Friday, June 22, 2018 10:15:55 AM
To: r-help-es@r-project.org
Subject: [R-es] loop con matriz que cambia de nombre


Buenos días. Quiero hacer un for (j), anidado en otro for (i). En el
2º for, en cada iteración ha de crear una matriz vacía: mat <-
matrix(nrow=nrow(data),ncol=19) pero llamándola de forma distinta cada
vez. El nombre ha de ser: paste("D",i,colnames(Data[j]),sep=""). Llevo
un rato haciendo pruebas pero no me sale. A ver si alguien pudiera
ayudarme,
gracias,
Manuel



























.
--
Dr Manuel Mendoza
Department of Biogeography and Global Change
National Museum of Natural History (MNCN)
Spanish Scientific Council (CSIC)
C/ Serrano 115bis, 28006 MADRID
Spain

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




--
Dr Manuel Mendoza
Department of Biogeography and Global Change
National Museum of Natural History (MNCN)
Spanish Scientific Council (CSIC)
C/ Serrano 115bis, 28006 MADRID
Spain

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





--
Saludos,
Carlos Ortega
www.qualityexcellence.es





--
Marcelino de la Cruz Rot
Depto. de Biología y Geología
Física y Química Inorgánica
Universidad Rey Juan Carlos
Móstoles España

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


Re: [R-es] loop con matriz que cambia de nombre

2018-06-25 Thread Manuel Mendoza
Gracias Javier. Como explicaba en mi contestación a Carlos, el  
problema no está en escribir muchas líneas, ni en rizar el rizo,  
claro. El proceso se lo tengo que aplicar a unas cuantas bases de  
datos, y cada una de ellas me lleva un buen rato porque tengo que  
hacerlo con 9 criterios distintos. Si consigo hacer un loop que me  
haga los 9, que es lo que intento, me ahorrará tiempo.

Manuel



Quoting Javier Marcuzzi :


Estimado Manuel

Justo ahora estoy trabajando en un proceso automatizado con código, pero la
mayoría de las veces tengo ciento de líneas donde mucho es copiar y pegar
más la modificación de una o dos palabras, podría ser un proceso que se
ejecute según criterios hasta la condición, pero la verdad que el objetivo
no es ganar un concurso de ingenio escribiendo código. Usted quiere entrar
en una parte donde R tiene demasiadas posibilidades y criterios,
posiblemente en eso python es más claro. Yo sí tengo que copiar y pegar
cientos de líneas antes que un bucle para acomodar datos, lo hago, prefiero
cientos de bucles pequeños en muchas líneas que pueda leer, antes que pocas
líneas con bucles anidados, aunque el código parezca de principiante.

Javier Rubén Marcuzzi

El dom., 24 de jun. de 2018 4:23 PM, Manuel Mendoza 
escribió:



Gracias Javier, pero creo que si no consigo que me lo haga todo de una
vez con un loop, me merece más la pena hacerlo como hasta ahora, una a
una.
Manuel



Quoting Javier Marcuzzi :

> Estimado Manuel Mendoza
>
> No sería lo ideal, pero de pronto podría ir guardando en json, que es una
> forma no estructurada, luego toma los datos recorriendo este y crea una
> estructura de dataframe para continuar.
>
> Javier Rubén Marcuzzi
>
> El sáb., 23 jun. 2018 a las 8:04, Manuel Mendoza ()
> escribió:
>
>>
>> Bien, Carlos, lo de ir metiendo las dfs en una lista parece buena
>> idea, y después puedo fusionarlas con un cbind, tal y como hago ahora
>> mismo, después de crear cada una de ellas independientemente. Son 9
>> dfs, y obtener cada una de ellas toma bastante tiempo de computación.
>> Lo que quiero es que me haga las 9 en un loop. El problema es que si
>> no les pone nombres distintos a las variables, después no puedo
>> identificarlas, y si les tengo que cambiar yo el nombre, no me merece
>> la pena hace el loop.
>>
>>
>>
>> Quoting "Carlos J. Gil Bellosta" :
>>
>> > Es que no quieres crear objetos con nombres raros en tu entorno. Lo
que
>> > quieres hacer es crear una lista de matrices (o dfs). El consejo
anterior
>> > te explicaba con detalle cómo dispararte en el pie. Realmente, quieres
>> > hacer otra cosa.
>> >
>> > El vie., 22 jun. 2018 a las 19:53, Manuel Mendoza (<
>> mmend...@mncn.csic.es>)
>> > escribió:
>> >
>> >>
>> >> Funciona, me crea una matriz en cada iteración, con un nombre que
>> >> incluye el nº de la iteración. Me surge ahora el problema de que,
>> >> dentro del mismo bucle la quiero convertir en df y ponerle nombre a
>> >> las columnas, y como el nombre de la matriz es distinto cada vez, no
>> >> sé cómo hacerlo. Supongo que se hará todo al crearla, pero no sé
cómo.
>> >>
>> >> Un problema adicional es que las variables (columnas) también han de
>> >> llevar la "i" incluida en el nombre, porque al final se fusionan
todas
>> >> las dfs y no se puede repetir el nombre de las variables.
>> >>
>> >> Gracias una vez más.
>> >>
>> >>
>> >>
>> >>
>> >> Quoting Jesús Para Fernández :
>> >>
>> >> > Con assing y un paste0
>> >> >
>> >> > Mete dentro del bucle esto
>> >> >
>> >> > for(i in 1:7){
>> >> > assign(paste0('matriz',i),matrix(0,ncol=5,nrow=3))
>> >> >
>> >> > }
>> >> >
>> >> > Con eso generarias 7 matrices de 5x3, llamadas matriz1, matriz2,...
>> >> >
>> >> > Obtener Outlook para Android<https://aka.ms/ghei36>
>> >> >
>> >> > 
>> >> > From: R-help-es  on behalf of
>> >> > Manuel Mendoza 
>> >> > Sent: Friday, June 22, 2018 10:15:55 AM
>> >> > To: r-help-es@r-project.org
>> >> > Subject: [R-es] loop con matriz que cambia de nombre
>> >> >
>> >> >
>> >> > Buenos días. Quiero hacer un for (j), anidado en otro for (i). En
el
>> >> > 2º for, en cada iteración ha de crear una matriz vacía: mat <-
>> >> > matrix(nrow=nrow(dat

Re: [R-es] loop con matriz que cambia de nombre

2018-06-25 Thread Manuel Mendoza
Gracias Carlos, eso lo sé. El problema, probablemente una chorrada, es  
que para cambiarle el nombre a las variables (de acuerdo a un patrón,  
si, que incluye el nº de la iteración), debo indicar el nombre de la  
df, pero éste no es siempre el mismo. Puedo darle un nombre fijo a la  
df, ponerle el nombre a las variables, y al final del loop cambiarle  
el nombre a la df, pero tampoco sé cómo ponerle un nombre nuevo que  
incluye paste + el nº de iteración de los dos loops anidados. Sé como  
crear ese nombre, con paste, pero no cómo ponérselo. Al decirlo así  
parece una tontería, y a lo mejor lo es, pero me tiré un rato  
intentándolo y no pude. Por eso acudí a vosotros.

Manuel


Quoting Carlos Ortega :


Hola,

En cada iteración de tu bucle, puedes:

   - Cambiar la matriz a data.frame.
   - Nombrar las columnas incluyendo si quieres el número de la iteración
   del bucle (tu "i").
  - Esto lo puedes hacer utiizando la función "paste()".
  - No sé si los nombres de las variables, en cada iteración han de
  seguir algún patrón.


Saludos,
Carlos Ortega
www.qualityexcellence.es

El 22 de junio de 2018, 19:53, Manuel Mendoza 
escribió:



Funciona, me crea una matriz en cada iteración, con un nombre que incluye
el nº de la iteración. Me surge ahora el problema de que, dentro del mismo
bucle la quiero convertir en df y ponerle nombre a las columnas, y como el
nombre de la matriz es distinto cada vez, no sé cómo hacerlo. Supongo que
se hará todo al crearla, pero no sé cómo.

Un problema adicional es que las variables (columnas) también han de
llevar la "i" incluida en el nombre, porque al final se fusionan todas las
dfs y no se puede repetir el nombre de las variables.

Gracias una vez más.




Quoting Jesús Para Fernández :

Con assing y un paste0


Mete dentro del bucle esto

for(i in 1:7){
assign(paste0('matriz',i),matrix(0,ncol=5,nrow=3))

}

Con eso generarias 7 matrices de 5x3, llamadas matriz1, matriz2,...

Obtener Outlook para Android<https://aka.ms/ghei36>


From: R-help-es  on behalf of Manuel
Mendoza 
Sent: Friday, June 22, 2018 10:15:55 AM
To: r-help-es@r-project.org
Subject: [R-es] loop con matriz que cambia de nombre


Buenos días. Quiero hacer un for (j), anidado en otro for (i). En el
2º for, en cada iteración ha de crear una matriz vacía: mat <-
matrix(nrow=nrow(data),ncol=19) pero llamándola de forma distinta cada
vez. El nombre ha de ser: paste("D",i,colnames(Data[j]),sep=""). Llevo
un rato haciendo pruebas pero no me sale. A ver si alguien pudiera
ayudarme,
gracias,
Manuel



























.
--
Dr Manuel Mendoza
Department of Biogeography and Global Change
National Museum of Natural History (MNCN)
Spanish Scientific Council (CSIC)
C/ Serrano 115bis, 28006 MADRID
Spain

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




--
Dr Manuel Mendoza
Department of Biogeography and Global Change
National Museum of Natural History (MNCN)
Spanish Scientific Council (CSIC)
C/ Serrano 115bis, 28006 MADRID
Spain

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





--
Saludos,
Carlos Ortega
www.qualityexcellence.es



--
Dr Manuel Mendoza
Department of Biogeography and Global Change
National Museum of Natural History (MNCN)
Spanish Scientific Council (CSIC)
C/ Serrano 115bis, 28006 MADRID
Spain

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


Re: [R-es] loop con matriz que cambia de nombre

2018-06-24 Thread Javier Marcuzzi
Estimado Manuel

Justo ahora estoy trabajando en un proceso automatizado con código, pero la
mayoría de las veces tengo ciento de líneas donde mucho es copiar y pegar
más la modificación de una o dos palabras, podría ser un proceso que se
ejecute según criterios hasta la condición, pero la verdad que el objetivo
no es ganar un concurso de ingenio escribiendo código. Usted quiere entrar
en una parte donde R tiene demasiadas posibilidades y criterios,
posiblemente en eso python es más claro. Yo sí tengo que copiar y pegar
cientos de líneas antes que un bucle para acomodar datos, lo hago, prefiero
cientos de bucles pequeños en muchas líneas que pueda leer, antes que pocas
líneas con bucles anidados, aunque el código parezca de principiante.

Javier Rubén Marcuzzi

El dom., 24 de jun. de 2018 4:23 PM, Manuel Mendoza 
escribió:

>
> Gracias Javier, pero creo que si no consigo que me lo haga todo de una
> vez con un loop, me merece más la pena hacerlo como hasta ahora, una a
> una.
> Manuel
>
>
>
> Quoting Javier Marcuzzi :
>
> > Estimado Manuel Mendoza
> >
> > No sería lo ideal, pero de pronto podría ir guardando en json, que es una
> > forma no estructurada, luego toma los datos recorriendo este y crea una
> > estructura de dataframe para continuar.
> >
> > Javier Rubén Marcuzzi
> >
> > El sáb., 23 jun. 2018 a las 8:04, Manuel Mendoza ( >)
> > escribió:
> >
> >>
> >> Bien, Carlos, lo de ir metiendo las dfs en una lista parece buena
> >> idea, y después puedo fusionarlas con un cbind, tal y como hago ahora
> >> mismo, después de crear cada una de ellas independientemente. Son 9
> >> dfs, y obtener cada una de ellas toma bastante tiempo de computación.
> >> Lo que quiero es que me haga las 9 en un loop. El problema es que si
> >> no les pone nombres distintos a las variables, después no puedo
> >> identificarlas, y si les tengo que cambiar yo el nombre, no me merece
> >> la pena hace el loop.
> >>
> >>
> >>
> >> Quoting "Carlos J. Gil Bellosta" :
> >>
> >> > Es que no quieres crear objetos con nombres raros en tu entorno. Lo
> que
> >> > quieres hacer es crear una lista de matrices (o dfs). El consejo
> anterior
> >> > te explicaba con detalle cómo dispararte en el pie. Realmente, quieres
> >> > hacer otra cosa.
> >> >
> >> > El vie., 22 jun. 2018 a las 19:53, Manuel Mendoza (<
> >> mmend...@mncn.csic.es>)
> >> > escribió:
> >> >
> >> >>
> >> >> Funciona, me crea una matriz en cada iteración, con un nombre que
> >> >> incluye el nº de la iteración. Me surge ahora el problema de que,
> >> >> dentro del mismo bucle la quiero convertir en df y ponerle nombre a
> >> >> las columnas, y como el nombre de la matriz es distinto cada vez, no
> >> >> sé cómo hacerlo. Supongo que se hará todo al crearla, pero no sé
> cómo.
> >> >>
> >> >> Un problema adicional es que las variables (columnas) también han de
> >> >> llevar la "i" incluida en el nombre, porque al final se fusionan
> todas
> >> >> las dfs y no se puede repetir el nombre de las variables.
> >> >>
> >> >> Gracias una vez más.
> >> >>
> >> >>
> >> >>
> >> >>
> >> >> Quoting Jesús Para Fernández :
> >> >>
> >> >> > Con assing y un paste0
> >> >> >
> >> >> > Mete dentro del bucle esto
> >> >> >
> >> >> > for(i in 1:7){
> >> >> > assign(paste0('matriz',i),matrix(0,ncol=5,nrow=3))
> >> >> >
> >> >> > }
> >> >> >
> >> >> > Con eso generarias 7 matrices de 5x3, llamadas matriz1, matriz2,...
> >> >> >
> >> >> > Obtener Outlook para Android<https://aka.ms/ghei36>
> >> >> >
> >> >> > 
> >> >> > From: R-help-es  on behalf of
> >> >> > Manuel Mendoza 
> >> >> > Sent: Friday, June 22, 2018 10:15:55 AM
> >> >> > To: r-help-es@r-project.org
> >> >> > Subject: [R-es] loop con matriz que cambia de nombre
> >> >> >
> >> >> >
> >> >> > Buenos días. Quiero hacer un for (j), anidado en otro for (i). En
> el
> >> >> > 2º for, en cada iteración ha de crear una matriz vacía: mat <-
> >>

Re: [R-es] loop con matriz que cambia de nombre

2018-06-24 Thread Carlos Ortega
Hola,

En cada iteración de tu bucle, puedes:

   - Cambiar la matriz a data.frame.
   - Nombrar las columnas incluyendo si quieres el número de la iteración
   del bucle (tu "i").
  - Esto lo puedes hacer utiizando la función "paste()".
  - No sé si los nombres de las variables, en cada iteración han de
  seguir algún patrón.


Saludos,
Carlos Ortega
www.qualityexcellence.es

El 22 de junio de 2018, 19:53, Manuel Mendoza 
escribió:

>
> Funciona, me crea una matriz en cada iteración, con un nombre que incluye
> el nº de la iteración. Me surge ahora el problema de que, dentro del mismo
> bucle la quiero convertir en df y ponerle nombre a las columnas, y como el
> nombre de la matriz es distinto cada vez, no sé cómo hacerlo. Supongo que
> se hará todo al crearla, pero no sé cómo.
>
> Un problema adicional es que las variables (columnas) también han de
> llevar la "i" incluida en el nombre, porque al final se fusionan todas las
> dfs y no se puede repetir el nombre de las variables.
>
> Gracias una vez más.
>
>
>
>
> Quoting Jesús Para Fernández :
>
> Con assing y un paste0
>>
>> Mete dentro del bucle esto
>>
>> for(i in 1:7){
>> assign(paste0('matriz',i),matrix(0,ncol=5,nrow=3))
>>
>> }
>>
>> Con eso generarias 7 matrices de 5x3, llamadas matriz1, matriz2,...
>>
>> Obtener Outlook para Android<https://aka.ms/ghei36>
>>
>> ____
>> From: R-help-es  on behalf of Manuel
>> Mendoza 
>> Sent: Friday, June 22, 2018 10:15:55 AM
>> To: r-help-es@r-project.org
>> Subject: [R-es] loop con matriz que cambia de nombre
>>
>>
>> Buenos días. Quiero hacer un for (j), anidado en otro for (i). En el
>> 2º for, en cada iteración ha de crear una matriz vacía: mat <-
>> matrix(nrow=nrow(data),ncol=19) pero llamándola de forma distinta cada
>> vez. El nombre ha de ser: paste("D",i,colnames(Data[j]),sep=""). Llevo
>> un rato haciendo pruebas pero no me sale. A ver si alguien pudiera
>> ayudarme,
>> gracias,
>> Manuel
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>> .
>> --
>> Dr Manuel Mendoza
>> Department of Biogeography and Global Change
>> National Museum of Natural History (MNCN)
>> Spanish Scientific Council (CSIC)
>> C/ Serrano 115bis, 28006 MADRID
>> Spain
>>
>> ___
>> R-help-es mailing list
>> R-help-es@r-project.org
>> https://stat.ethz.ch/mailman/listinfo/r-help-es
>>
>
>
> --
> Dr Manuel Mendoza
> Department of Biogeography and Global Change
> National Museum of Natural History (MNCN)
> Spanish Scientific Council (CSIC)
> C/ Serrano 115bis, 28006 MADRID
> Spain
>
> ___
> R-help-es mailing list
> R-help-es@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-help-es
>



-- 
Saludos,
Carlos Ortega
www.qualityexcellence.es

[[alternative HTML version deleted]]

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


  1   2   3   4   5   6   7   8   9   >