samedi 10 août 2019

Using if statement inside function in R

I am trying to iterate over a given set of values where for every new value the loop begins to add number by restarting from 1. The code is given below.

rdt2 <- function(z){
  i = 1
  k = 1
  v = 0
  b = z[1]
  while (i <= length(z)){
    v[i] = z[i]*100 + k
    if (v[i] == b){
      k = k + 1
    }
    if (v[i] != b){
      b[i] = v[i]
      k = 1
    }
    i = i + 1
  }
  return(v)
}

This code throws values but not the incremented ones. Let the z be

c(2150L, 2151L, 2151L, 2151L, 2151L, 2151L, 2151L, 2152L, 2153L, 
2152L, 2152L, 2152L, 2152L, 2152L, 2152L, 2152L, 2152L, 2154L, 
2155L, 2155L, 2155L, 2155L, 2155L, 2155L, 2155L, 2155L, 2156L, 
2156L, 2156L, 2156L, 2156L, 2156L)

As you can see there are numbers with different rfrequencies. I want for each number the loop to run by that frequency to get new set of numbers. This is intended for populating column A based on column B.

Aucun commentaire:

Enregistrer un commentaire