'How to speed up this loop in R?

I'm trying to analyze each sample with different types, like using the 'table' function for sample 1 to type-a, sample 1 to type-b ... , so I wrote 2 loops to do this. But when the number of samples and types increase, it is really time-consuming. So if there are any methods to increase the speed? Thank you~ enter image description here

For example,like below,

for (i in seq_len(nlevels(types))){
  for(z in seq_len(ncol(data))){
    ......
  }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source