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")
0

1 Answer 1

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)))
Sign up to request clarification or add additional context in comments.

6 Comments

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 Updated with a apply family function
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.
Thank you both for your input. I will keep working on it.
@akrun I was definitely going to. It didn't let me accept it until a few minutes after your comment.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.