Writing a function in in R

Viewed 81

I am doing an exercise to practice writing functions.

I'm trying to figure out the general code before writing the function that reproduces the output from the table function. So far, I have the following:

set.seed(111) 
vec <- as.integer(runif(10, 5, 20)) 

x <- sort(unique(vec))

for (i in x) {
   c <- length(x[i] == vec[i]) 
   print(c) 
}

But this gives me the following output:

[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1

I don't think I'm subsetting correctly in my loop. I've been watching videos, but I'm not quite sure where I'm going wrong. Would appreciate any insight!

Thanks!

3 Answers

We can sum the logical vector concatenate it to count

count <- c()
for(number in x) count <- c(count, sum(vec == number)) 
count
#[1] 3 1 4 1 5 4 3 2 7

In the OP's for loop, it is looping over the 'x' values and not on the sequence of 'x'

If we do

for(number in x) count <- c(count, length(vec[vec == number])) 

it should work as well

You can try sapply + setNames to achieve the same result like table, i.e.,

count <- sapply(x, function(k) setNames(sum(k==vec),k))

or

count <- sapply(x, function(k) setNames(length(na.omit(match(vec,k))),k))

such that

> count
1 2 3 4 5 6 7 8 9 
3 1 4 1 5 4 3 2 7 

Here is a solution without using unique and with one pass through the vector (if only R was fast with for loops!):

count = list()
for (i in vec) {
  val = as.character(i)
  if (is.null(count[[val]]))
    count[[val]] = 1
  else
    count[[val]] =  count[[val]] + 1
}
unlist(count)
Related