2
A simple doubt,
How to have the (new) vector briefly to avoid:
for(v in i$checkout) {
c(vector, v$name) -> vector
c(vector_item, v$qty) -> vector_item
}
Error in c(vector_item, v$Qty) : Object 'vector_item' not found
2
A simple doubt,
How to have the (new) vector briefly to avoid:
for(v in i$checkout) {
c(vector, v$name) -> vector
c(vector_item, v$qty) -> vector_item
}
Error in c(vector_item, v$Qty) : Object 'vector_item' not found
1
To solve the immediate problem, correct the error, as I say in the question comment can create the vector
vector_item <- NULL
or, alternatively,
vector_item <- c()
before the cycle for
.
But it is very bad idea to extend the vectors within the cycles, it is very slow because it forces R to run the memory management routines as many times as the vector size changes.
It is much better to reserve memory before the cycle, creating a result vector of the appropriate length. See in this simple example the difference it makes.
fun1 <- function(x){
y <- NULL
for(i in x){
y <- c(y, 2*i)
}
y
}
fun2 <- function(x){
y <- numeric(length(x))
for(i in seq_along(x)){
y[i] <- 2*x[i]
}
y
}
library(ggplot2)
library(microbenchmark)
n <- 1e3
x <- 1:n
mb <- microbenchmark(
mem_extendida = fun1(x),
mem_reservada = fun2(x)
)
print(mb, order = 'median')
#Unit: microseconds
# expr min lq mean median uq max neval cld
# mem_reservada 117.966 118.867 135.1909 137.0395 140.407 226.058 100 a
# mem_extendida 2135.724 2187.807 2698.3200 2217.5420 2277.828 9311.886 100 b
autoplot(mb)
worked, thank you very much
Browser other questions tagged array r vector
You are not signed in. Login or sign up in order to post.
vector_item
already existed? Why do you only update like this in R if the object already exists... Try to create an empty vector or the size ofv$qty
before the for.– Jorge Mendes
Can create
vector_item <- NULL
orvector_item <- c()
before the cyclefor
.– Rui Barradas