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

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

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

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>

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 ]

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:

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

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

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

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.

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,

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

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])) +

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

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

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

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

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

2021-03-30 Thread Mika Hamari
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 y

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

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

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

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

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

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.

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

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"

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

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"

Re: [R] If Loop I Think

2019-10-24 Thread William Michels via R-help
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(a

Re: [R] If Loop I Think

2019-10-23 Thread PIKAL Petr
lf 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 >

Re: [R] If Loop I Think

2019-10-22 Thread Jim Lemon
w 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: >

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

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

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,

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

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

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

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

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 >

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

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

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

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.

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,

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.

Re: [R] For Loop

2018-09-23 Thread Jeff Newmiller
r 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

Re: [R] For Loop

2018-09-23 Thread Duncan Murdoch
ove 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. Whet

Re: [R] For Loop

2018-09-23 Thread Sorkin, John
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 se

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.

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

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

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

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

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

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

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(

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

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

Re: [R] For loop with multiple iteration indexes

2018-09-11 Thread David L Carlson
: 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

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 =

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

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

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

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

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

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

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

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

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

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,

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

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

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

2018-06-24 Thread Manuel Mendoza
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

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

2018-06-23 Thread 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ó:

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

2018-06-23 Thread Manuel Mendoza
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

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

2018-06-22 Thread 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 () escribió:

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

2018-06-22 Thread Manuel Mendoza
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.

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

2018-06-22 Thread Manuel Mendoza
Gracias Jesú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

Re: [R] nested loop

2017-09-09 Thread Ek Esawi
I would try fininterval as well. It should do what you have asked provided that you take care of the issue Ulrik pointed out. Best of luck--EK On Fri, Sep 8, 2017 at 6:15 AM, Hemant Sain wrote: > i have a vector containing values ranging from 0 to 24 > i want to create

Re: [R] Nested loop R code

2017-09-08 Thread Ulrik Stervbo
Hi Hemant, please write to the r-help list in the future. Look at the cut () function to solve your problem. Also, you have a problem in your example - 5 is placed in two different categories. HTH Ulrik On Fri, 8 Sep 2017 at 12:16 Hemant Sain wrote: > i have a vector

Re: [R] R loop function in Tableau

2017-07-07 Thread David Winsemius
> On Jul 6, 2017, at 2:19 PM, Dai, Shengyu wrote: > > Hi R helpers, > > > > I hope this email finds you well. > > > > I am having trouble with R loop function in Tableau. > There is no "R loop function". (There is an R `for`-function.) If you are having trouble with code

Re: [R] For loop

2017-06-22 Thread Nordlund, Dan (DSHS/RDA)
For a reproducible example, you need to give us some example data, at least dput(head(leafbiom97)) dput(head(Litterfall_Ahmed97)) dput(head(GPP_Ahmed13)) Dan Daniel Nordlund, PhD Research and Data Analysis Division Services & Enterprise Support Administration Washington State Department of

Re: [R] For loop

2017-06-22 Thread Rui Barradas
Hello, Without correcting your code, it's obvious that the expressions like leafbiom97$Date == "i" and all others with"i" and "i - 1" are wrong. leafbiom97$Date is of class Date, not character. And, besides, for(i in ...) makes of i a numeric variable that has nothing to do with "i". This "i"

Re: [R] for loop in R

2017-01-12 Thread jennifer . sheng2002
That is right, Bob. Only one loop for now, since I do not know how to set up the 2nd loop. Any advice from the community? Thank you! Sent from my iPhone > On Jan 12, 2017, at 4:49 PM, Robert Sherry wrote: > > I only see one for loop in your code. I am wondering if you

Re: [R] for loop in R

2017-01-12 Thread Robert Sherry
I only see one for loop in your code. I am wondering if you want a second for loop based upon the length of newdata. I would also think that you do not need the second call to set.seed. Bob On 1/12/2017 4:44 PM, Jennifer Sheng wrote: Dear friends, I am working on a double loop using for.

Re: [R] for loop is looping only once

2016-11-17 Thread Duncan Murdoch
On 17/11/2016 6:26 AM, Ulrik Stervbo wrote: Hi Georg, Your for loop iterates over just one value, to get it to work as you intend use for(item in 1:length(kpis)){} That usually works, but fails often enough that we recommend using for (item in seq_along(kpis)) {} (The failures happen if

Re: [R] for loop is looping only once

2016-11-17 Thread Ulrik Stervbo
Hi Georg, Your for loop iterates over just one value, to get it to work as you intend use for(item in 1:length(kpis)){} HTH Ulrik On Thu, 17 Nov 2016 at 12:18 wrote: > Hi All, > > I need to execute a loop on variables to compute several KPIs. > Unfortunately the for

Re: [R] Simple loop problem

2016-10-31 Thread William Dunlap via R-help
Did you mean 'tolower' instead of 'to lower' in your example? Or is there a similarly named function that converts the levels of a factor to lower case instead of converting the factor to a character vector and then lower-casing that? > d %>% dplyr::mutate_if(is.factor, tolower) NumF1 F2 1

Re: [R] Simple loop problem

2016-10-31 Thread William Dunlap via R-help
Use tolower on the levels of the factor columns. E.g., > d <- data.frame(Num=1:3, F1=c("One","Two","Three"), F2=c("A","B","a")) > str(d) 'data.frame': 3 obs. of 3 variables: $ Num: int 1 2 3 $ F1 : Factor w/ 3 levels "One","Three",..: 1 3 2 $ F2 : Factor w/ 3 levels "a","A","B": 2 3 1 >

Re: [R] Simple loop problem

2016-10-31 Thread David L Carlson
This looks like homework and r-help has a policy of not providing answers for homework. But first you need to research what happens when you convert a data frame to a matrix. Also in your loop, i is a numeric value between 1 and the length of x: What is x (what class)? What is the length of

Re: [R] better loop for simulation

2016-06-18 Thread Dalthorp, Daniel
try: n.questions <- 10 # or however many you want mult.choice <- 2 scores <- rbinom(1000, size = n.questions, prob = 1/mult.choice) On Sat, Jun 18, 2016 at 3:12 PM, Naresh Gurbuxani < naresh_gurbux...@hotmail.com> wrote: > I want to calculate a function many times over. My solution below

Re: [R] better loop for simulation

2016-06-18 Thread Duncan Murdoch
On 18/06/2016 6:12 PM, Naresh Gurbuxani wrote: I want to calculate a function many times over. My solution below works, but does not seem very elegant. # my function to run many times over stud.score <- function(n.questions, mult.choice = 2) { prob.success <- 1 / mult.choice

Re: [R] better loop for simulation

2016-06-18 Thread jim holtman
use replicate: > stud.score <- function(n.questions, mult.choice = 2) { + prob.success <- 1 / mult.choice + answers <- (runif(n.questions) < prob.success) + return(sum(answers)) + } > > # create 1000 results > result <- replicate(1000, stud.score(10)) > > # look at

Re: [R] R [loop statement ]

2016-04-16 Thread Jim Lemon
Hi tan sj, It is by no means easy to figure out what you want without the code, but If I read your message correctly, you can run the loops either way. When you have nested loops producing output, it is often a good idea to include the parameters for each run in the output as well as the result so

Re: [R] MACRO-LOOP in R

2016-02-19 Thread Thierry Onkelinx
Please keep the mailinglist in cc. You should be able to solve this after reading the helpfiles of ?dplyr::mutate and ?tidyr::spread Best regards, ir. Thierry Onkelinx Instituut voor natuur- en bosonderzoek / Research Institute for Nature and Forest team Biometrie & Kwaliteitszorg / team

Re: [R] MACRO-LOOP in R

2016-02-18 Thread Jeff Newmiller
What a mess. Transposing factors is highly unlikely to lead to sensible results. Did you look at str( x123 ) as your example created it? x <- data.frame( a=c(1,2,3), b=c("1","2","3"), stringsAsFactors=FALSE ) x123new <- setNames( as.data.frame( t( x[ , "b" ] ) ), paste( "b", 1:3, sep="_" ) )

Re: [R] for loop

2016-01-12 Thread Jim Lemon
Hi maryam (firoozi), Apart from the fact that you are overworking your sires (or the more realistic scenario of differential mating success) you can achieve the 700:30 ratio in this simple way: sires<-paste("Sire",1:30,sep="") dams<-paste("Dam",1:700,sep="")

Re: [R] for loop

2016-01-12 Thread Michael Dewey
Dear Maryam Please keep the list cc'ed in as others will have better answers than me. If dam has 700 members then sample (dam) gives you a random permutation of dams, each once. I did not understand the second part as i do not think you can have 30 sires each occurring 20 times. Did you

Re: [R] for loop

2016-01-12 Thread Michael Dewey
Dear Maryam sample(dam) would give you a random permutation of dams sample(c(sire, sire)) would give you a random permutation of sires, each twice. Does that help? On 12/01/2016 05:53, maryam firoozi via R-help wrote: Dear mr/madam I want to mak a matrix with 10 row and 3 column . this

Re: [R] For loop coding

2015-12-04 Thread PIKAL Petr
Hi > -Original Message- > From: R-help [mailto:r-help-boun...@r-project.org] On Behalf Of Saba > Sehrish via R-help > Sent: Friday, December 04, 2015 11:21 AM > To: r-help@r-project.org > Subject: [R] For loop coding > > Hi > > I will be grateful if someone please tell me the programming

  1   2   3   4   5   6   7   >