More efficient way to separate numbers in r? -
More efficient way to separate numbers in r? -
i have function doing want inefficient , wonder if there more efficient way that.
the thing want improve separate number , save info different variables, sum them. code have is:
indep <- as.numeric() first <- as.numeric() sec <- as.numeric() 3rd <- as.numeric() for(i in 1:nmat){ first[i] <- as.numeric(substr(matrix[i], 1, 1)) sec[i] <- as.numeric(substr(matrix[i],3, 3)) third[i] <- as.numeric(substr(matrix[i], 4, 4)) indep[i] <- sum(first[i],sec[i],third[i],na.rm=t) } > illustration if have numbers(234,361) > want in first->(2,3), > in second->(3,6), > third->(4,1) , in > ind->(2+3+4=9,3+6+1=10)
numbers have more 6 digits , 1 point 1.923442334, info in big matrix nxn
hope understand want, give thanks you.
if numbers have each 3 digits, can avoid string manipulation , utilize basic arithmetic. instance:
numbers<-c(234,361) #this give matrix in each column has digits of each number mymatrix<-matrix((rep(numbers,each=3) %/% 10^(2:0))%%10,nrow=3) #obtain sum of digits: colsums(mymatrix)
this approach orders of magnitude faster every 1 uses string manipulation.
r
Comments
Post a Comment