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)
}
}
Here's an alternative that uses base R and avoids for loops.
x <- c(11, 2354, 55, 432, 1112, 320)
countintegers <- function(x) {
xpasted <- paste(x, collapse ='')
xsplit <- strsplit(xpasted, '')
xtable <- table(xsplit)
empty <- table(seq(0,9)) - 1
result <- sapply(names(empty), function(n) xtable[n] + empty[n])
result[is.na(result)] <- 0
as.integer(result)
}
countintegers(x)
#1 5 4 3 2 3 0 0 0 0
We can also use some regex for this, by pasting all the numbers into one string and then counting how many characters are removed by gsub()
if a digit is replaced with "":
digitCounter <- function(x) {
x <- paste(x, collapse = "")
l <- vector()
for(i in 0:9) {l[i+1] <- nchar(x) - nchar(gsub(i, "", x))}
return(l)
}
I have constructed this function. This function will give how many digits of 0, 1, 2, ..., 9 appears in a vector as needed. The "main engine" of this function is the str_count()
from library stringr
.
library(stringr)
count_digits = function(x){
y <- rep(0, 10)
for(digit in 0:9){
y[digit+1] <- sum(str_count(x,as.character(digit)))
}
y
}
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.