Is it possible to loop inside a structure "inside (...)"?

Thanks for all the help I received from a simple read.

I am not happy with my R cycles when I deal with only one data.frame file because I write again and again the name of the data framework that inflates my R code.

Here is a stupid example:

x<- rep(NA,10) y <- 1:10 dat <- data.frame(x,y) for(i in 2:nrow(dat)){ dat$x[i] <- dat$y[i] + dat$y[i-1] } 

So I want to get rid of dat$ -bit. External loops can be done using within() , but I'm not quite sure if you really can do this with R. I tried this:

 remove(x,y) # In order to avoid accidental usage of the initial vectors within(dat,{ for(i in 2:nrow(dat)){ x[i] <- y[i] + y[i-1] }}) 

The result is as follows:

  xyi 1 NA 1 10 2 3 2 10 3 5 3 10 4 7 4 10 5 9 5 10 6 11 6 10 7 13 7 10 8 15 8 10 9 17 9 10 10 19 10 10 

So the loop really worked, but just a new magic column.

Does anyone know (1) what is happening here and (2) how to handle such types of loops elegantly (a more complex example of wrapping within() around a loop, including several if() and failed btw calculations?

Thank you very much! SKR

+4
source share
1 answer

Ben answered your main question, noting that i is assigned by a for loop. You can see that this is the case by trying something like this:

 for(j in 1:3) cat("hi\n") hi hi hi > j [1] 3 

One option is to simply remove the unwanted variable i by specifying its NULL value:

 within(dat,{ for(i in 2:nrow(dat)){ x[i] <- y[i] + y[i-1] } i <- NULL }) 

Another is to use with() instead of within() :

 dat$x <- with(dat, { for(i in 2:nrow(dat)){ x[i] <- y[i] + y[i-1] } x }) 

Finally, although I understand that yours was a toy example, the best solution would be to very often avoid for loops:

 d <- data.frame(y=1:10) within(d, {x = y + c(NA, head(y, -1))}) # yx # 1 1 NA # 2 2 3 # 3 3 5 # 4 4 7 # 5 5 9 # 6 6 11 # 7 7 13 # 8 8 15 # 9 9 17 # 10 10 19 
+4
source

Source: https://habr.com/ru/post/1436465/


All Articles