1

This is a question about the utilization of apply. It is purely coincidental that a question of this nature has been answered. I am not looking for the easiest way to do it (which would have made it a duplicate). I wrote something random that can be solved using a loop. I am looking for how my problem can be written using apply.

In R, I'm having a really hard time getting out of the habit of always using loops. Here is a basic sample script I wrote. It takes the data and states the frequency of each unique number in the table.How can I accomplish the same thing with apply, if possible?

x <- c(1,3,4,7,8,10,1,2,3,4,4,6,7,8,8,1,2,3,7,8)
y <- data.frame(x)
z <- data.frame(unique(y)) #finds unique values
i <- nrow(z) #nrow for loop length

id <- 1:i
repped <- data.frame()
for (i in id){
    zz <- y[which(y[,1] == z[i,]),] #takes each value from z and finds rows with identical values
value <- length(zz)
repped <- rbind(repped, value)
}

yy <- data.frame(z, repped)
colnames(yy) <- c("number", "frequency")
Andrew
  • 7,201
  • 5
  • 25
  • 34

1 Answers1

2

We can use table to get the frequency of 'y' and wrap it with data.frame

 as.data.frame(table(y))

If we need an apply family function

data.frame(z=unique(y$x),repped= sapply(unique(y$x), 
       function(i) sum(y$x==i)))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • That is an extremely helpful function you just told me. I am now aware of how convoluted my method is, but my explicit question is how I would use apply instead of a loop in this situation? – Andrew Mar 01 '16 at 09:18
  • @Andrew Updated with a apply family function – akrun Mar 01 '16 at 09:22
  • 3
    If you are trying to get out of an habit of using loops, then don't develop a new habit of using `apply`. Instead, develop a habit to vectorize your code. – David Arenburg Mar 01 '16 at 09:22
  • Thank you both for your input. I will keep working on it. – Andrew Mar 01 '16 at 09:25
  • 1
    @akrun I was definitely going to. It didn't let me accept it until a few minutes after your comment. – Andrew Mar 01 '16 at 09:49
  • @Andrew Thanks for the comment. You are right. It takes some 10 mins or so. – akrun Mar 01 '16 at 09:51