Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 204798

The function in R that can calculate how many times a digit appears in a vector

$
0
0

So, for example, if I have a vector x <- c(11, 2354, 55, 432, 1112, 320), the function should return a vector that indicates how many times the digits 0, 1, 2, ..., 9 have appeared in x.

For 'x', the expected counts for digits 0,1,2..9 would be c(1, 5, 4, 3, 2, 3, 0, 0, 0, 0), because, 0 only appeared once in 320, 1 appeared 2 (in 11) + 3 (in 1112) = 5 and so on.

I am trying to make function like this, but I am not really good at R. Here is what I have attempted so far:

f <- function(x){
 if(is.vector(x) & length(x) > 0) {
 z <- c(0,0,0,0,0,0,0,0,0,0)
 n <- c(nchar(x))
 for(i in range(length(x))) {
   for(d in range(n[i])) {
     for (j in range(1:10)) {
       if(x[i]%%10 == j) {
         z <- replace(z, z == z[j], z[j]+1)
       }
     }
   x <- replace(x, x == x[i], x[i]%/%10)
  }
 }return(z) 
}
}

Viewing all articles
Browse latest Browse all 204798

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>