Hi!
I've observed that apply
family of functions are usually better than loops, and indeed there are some articles available online.
In one of my college assignments, I need to do a task for a large number of items, and in between them, I need to update a quantity. It takes long time, and so I thought to use sapply instead of a for
loop. But, after I implemented it, I noted that there are some problems with the output and verified that the updation is not occurring.
Though not at all comparable to my assignment, here's an illustration:
## using for loop
x <- 10
y <- c()
for (i in seq_len(length.out = x))
{
if (x > 5)
{
x <- (x - 1)
y[i] <- x
} else
{
y[i] <- x
}
}
cat('\nx:', x, '\ny:', y)
#>
#> x: 5
#> y: 9 8 7 6 5 5 5 5 5 5
## using sapply
x <- 10
y <- sapply(X = seq_len(length.out = x),
FUN = function(t)
{
if (x > 5)
{
x <- (x - 1)
return(x)
} else
{
return(x)
}
})
cat('\nx:', x, '\ny:', y)
#>
#> x: 10
#> y: 9 9 9 9 9 9 9 9 9 9
## using sapply with global variables
x <<- 10
y <- sapply(X = seq_len(length.out = x),
FUN = function(t)
{
if (x > 5)
{
x <<- (x - 1)
return(x)
} else
{
return(x)
}
})
cat('\nx:', x, '\ny:', y)
#>
#> x: 5
#> y: 9 8 7 6 5 5 5 5 5 5
Created on 2019-01-31 by the reprex package (v0.2.1)
I can update by defining global variables, as in the 3rd case above, but I don't want to do that (may be because I'm not comfortable with it).
Any help will be appreciated.