0
the columns and table values will be filled in as the cycle runs. Briefly, I have a table with customer data (BD) and another table with expected future values by age (ESP). And what the cycle does is, for an x-age client, go get all the expected values for the current age and future age that are in another table. In excel could do this quickly. How to improve cycle performance in R?
ESP table and BD table:
ESP
# A tibble: 10 x 2
IDADE ESP
<dbl> <dbl>
1 0 100000
2 1 99129
3 2 99057
4 3 99010
5 4 98977
6 5 98948
7 6 98921
8 7 98897
9 8 98876
10 9 98855
BD
IDADE_ACT
1 84
2 44
3 24
4 23
5 23
6 22
7 25
8 22
9 22
10 22
the R CODE I’m using
FUN <- function (BD, ESP) {
anos<-ncol(ESP)
n <- nrow(BD)
DF <- data.frame()
for (i in 1:n) {
idade <- BD[i, ]$IDADE_ACT
if (is.na(idade)) {DF[i, ] <- 0}
else {
j <- 1
while (j <= anos + 1) {
if (idade >= 0 && idade + j <= nrow(ESP)) {
DF[i, j] <- ESP[idade + j, 2]
} else{(DF[i, j] <- 0)}
j <- j + 1
}
}
}
colnames(DF) <- c(0:anos)
return(DF)
}
ESP
andBD
. You can edit the question with the output ofdput(head(ESP, 20))
and the same forBD
, please? 2) Withreturn
in the end this is a function; missing the beginning, the code is incomplete. How is the function called?– Rui Barradas
thanks for the alert. posted the wrong Cod and put an ex of the tables, but basically, wanted to do something very similar to vlookup in excel.
– Albano