Home > database >  loop through digits in a number and perform calculations
loop through digits in a number and perform calculations

Time:08-06

A = "883745"
N1 = as.numeric(substr(A , 1, 1))
N2 = as.numeric(substr(A , 2, 2))
N3 = as.numeric(substr(A , 3, 3))
N4 = as.numeric(substr(A , 4, 4))
N5 = as.numeric(substr(A , 5, 5))
N6 = as.numeric(substr(A , 6, 6))

I need to calculate

N1 *  nchar(A)      
N2 * (nchar(A) - 1)   
N3 * (nchar(A) - 2)   
N4 * (nchar(A) - 3)   
N5 * (nchar(A) - 4)   
N6 * (nchar(A) - 5)

How do I do this using loop in R?

CodePudding user response:

substring not substr is useful for these kind of vectorised substringing operations:

nc <- seq(nchar(A))
sum(as.numeric(substring(A, nc, nc)) * rev(nc))
#[1] 134

CodePudding user response:

A <- "883745"

First, when given this task, you need to break down the summation and look for pattern. In particular, pay attention to what is changing.

ans  = as.numeric(substr(A , 1, 1)) * (nchar(A) - 0)
ans  = as.numeric(substr(A , 2, 2)) * (nchar(A) - 1)
ans  = as.numeric(substr(A , 3, 3)) * (nchar(A) - 2)
ans  = as.numeric(substr(A , 4, 4)) * (nchar(A) - 3)
ans  = as.numeric(substr(A , 5, 5)) * (nchar(A) - 4)
ans  = as.numeric(substr(A , 6, 6)) * (nchar(A) - 5)

This can be summarized as:

ans  = as.numeric(substr(A , i, i)) * (nchar(A) - i   1), i = 1, 2, ..., 6

Freshman

Loop as it is.

ans <- 0
for (i in 1:6) {
  ans <- ans   as.numeric(substr(A , i, i)) * (nchar(A) - i   1)
}
ans
#[1] 134

Sophomore

Pre-compute the result of substring and nchar, then index them in the loop.

N <- as.numeric(substring(A, 1:6, 1:6))
L <- nchar(A) - (1:6)   1
ans <- 0
for (i in 1:6) {
  ans <- ans   N[i] * L[i]
}
ans
#[1] 134

Junior

Replace the loop by sum.

N <- as.numeric(substring(A, 1:6, 1:6))
L <- nchar(A) - (1:6)   1
ans <- sum(N * L)
ans
#[1] 134

Senior

Replace sum by crossprod.

N <- as.numeric(substring(A, 1:6, 1:6))
L <- nchar(A) - (1:6)   1
ans <- c(crossprod(N, L))
ans
#[1] 134

CodePudding user response:

Your code can be considerably simpler and no loop is necessary. This may be what you are trying to accomplish:

A <- 883745
len <- nchar(A)
N <- as.numeric(unlist(strsplit(as.character(A), "")))
N
# [1] 8 8 3 7 4 5
N * (len - 0:5)
# [1] 48 40 12 21  8  5
sum(N * (len - 0:5))
# [1] 134
  • Related