简体   繁体   中英

Partial/Custom sorting in R vector

I am trying to generate a 3 column array in R, with the following property- 1st column goes from 0 to 255, for a total of (256*256) times.

B_1 <- as.data.frame(rep.int(0:255,256*256))

3rd column has the exact same values as the first one, but sorted from least to greatest

B_3 <- as.data.frame(sort(B_1[,1],decreasing = FALSE))

But I cannot think of a simple algorithm for the column in between the two in which I want the following- Every value in B_2 should repeat for 256 sets of 0:255 in B1. In other words, as value increment in B_3, the value in B_2 is reset to 0, for 256 times. I can join the three vectors to make the array afterwards easily enough. The purpose is illustrated in the following piece of code.

j= 0
for (i in 1: 16777216){
  B_2[i,1]=j
  if(B_1[i,1]>B_1[i+1,1]){
    j = j + 1
   }
  if (j>255){
    j=0
  }

  }

But as you can imagine, for an array of this size, for loop is highly inefficient. I understand that tidyverse will probably have a method to do this easily, but I was hoping to find one within the base packages of R. Can this be done?

If I understand you correctly, this is what you need.

B_3 <- as.data.frame(rep(0:255, each=255))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM