Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement table() function as a user defined function

Tags:

r

x <- c(1,2,3,2,1)

table(x)
# x
# 1 2 3 
# 2 2 1

Outputs how many times each element occur in the vector.

I am trying to imitate the above function using function()

Below is my code:

TotalTimes = function(x){
  times = 0
  y = unique(x)
  for (i in 1:length(y)) {
    for (i in 1:length(x)) {
      if(y[i] == x[i])
      times = times + 1
    }
    return(times)
  }
}

What would be the right approach?

like image 409
Rohan Avatar asked May 30 '26 21:05

Rohan


1 Answers

Here's a one-liner, using rle():

f <- function(x) {
    with(rle(sort(x)), setNames(lengths, values))
}

f(c(1,2,3,2,1))
# 1 2 3 
# 2 2 1 

Alternatively, here's an option that's less "tricky", and is probably a better model for learning to code in an R-ish way:

f2 <- function(x) {
    ss <- sort(x)
    uu <- unique(ss)
    names(uu) <- uu
    sapply(uu, function(u) sum(ss == u))
}

f2(c(1,2,3,2,1))
# 1 2 3 
# 2 2 1 
like image 116
Josh O'Brien Avatar answered Jun 02 '26 15:06

Josh O'Brien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!