Thanks for all the help I got from just reading stuff.
I’m not happy with my R loops when I am only dealing within one data.frame because I have to write down the name of the dataframe over and over again which bloats up my R code.
Here is a silly 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 what I want to get rid of is that dat$ -bit. Outside loops this can neatly be done with within(), but I am not exactly sure whether you can actually do that with R. I tried it though:
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 output looks like this:
x y i
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 did actually work, it’s just that there is a new magical column.
Does anyone know (1) what is going on here and (2) how to elegantly deal with that kind of loops (a more complicated example wrapping within() around a loop including several if() statements and calculations failed btw?
Thanks a lot in advance!
skr
Ben answered your main question, by noting that
iis being assigned to by theforloop. You can see that that is so by trying something like this:One option is just to remove the unwanted
ivariable by making its valueNULL:Another is to use
with()instead ofwithin():Finally, though I realize yours was a toy example, the best solution will very often be to avoid
forloops altogether: