如何在R中循环中的最后一个元素后追加到列表?

时间:2019-06-21 18:56:49

标签: r list vector append add

我的向量名称为block_sizes=c(3,3,4),我想列出一个列表,其中block_sizes[1]的数字为1,block_sizes[2]的数字为2,而block_sizes[3]的数字为3,等

在此示例中,我应该将[3,3,4]赋予我的代码并获得[1,1,1,2,2,2,3,3,3,3]

我写了下面的代码,但是我不知道为什么它给了我[0,3,3,3,3]。我认为是因为我应该附加到vector的最后一个元素上,而我现在不是。任何输入表示赞赏。

vector=0
for (i in length(block_sizes )) {
  buf=rep.int(i,times =block_sizes[i])
  membership_vector=append(vector,buf)

  }```

2 个答案:

答案 0 :(得分:2)

由于 /* Wait till the main PLL is ready */ while((RCC->CR & RCC_CR_PLLRDY) == 0) { } #if defined (STM32F40_41xxx) || defined (STM32F427_437xx) || defined (STM32F429_439xx) /* Configure Flash prefetch, Instruction cache, Data cache and wait state */ FLASH->ACR = FLASH_ACR_PRFTEN | FLASH_ACR_ICEN |FLASH_ACR_DCEN |FLASH_ACR_LATENCY_5WS; #endif /* STM32F40_41xxx || STM32F42_43xxx */ #if defined (STM32F401xx) /* Configure Flash prefetch, Instruction cache, Data cache and wait state */ FLASH->ACR = FLASH_ACR_PRFTEN | FLASH_ACR_ICEN |FLASH_ACR_DCEN |FLASH_ACR_LATENCY_2WS; #endif /* STM32F401xx */ /* Select the main PLL as system clock source */ RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW)); RCC->CFGR |= RCC_CFGR_SW_PLL; /* Wait till the main PLL is used as system clock source */ while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS ) != RCC_CFGR_SWS_PLL); { } 参数是矢量化的,我们可以不加循环地使用rep

times

或者为了更快地实现

rep(seq_along(block_sizes), block_sizes)
#[1] 1 1 1 2 2 2 3 3 3 3

或者如果我们需要循环

rep.int(seq_along(block_sizes), times = block_sizes)
#[1] 1 1 1 2 2 2 3 3 3 3

数据

v1 <- c()
for(i in seq_along(block_sizes)) {
   v1 <- c(v1, rep.int(i, times = block_sizes[i]))
 }

答案 1 :(得分:2)

我们可以使用CustomUIView

mapply