samedi 10 août 2019

function for populating one column based on another column in R

For each string occurring n number of times in column A, I want to insert a 4-digit integer value in the column B. And, as the next string is checked and if it is a new string present in column A then column B has new integer +1 to be repeated against the string value of column A.

rftwo <- function(r, x){
  for (h in range(1, length(r))){
   b = r[h]
   a = r[h + 1]
   if (a == b) 
     x[h] = i
   h = h + 1
  }
  i = i + 1
}

Now as I apply in the following manner:

p1$ID_1 <- rftwo(p1$NAME_1, p1$ID_1)

I get an error as below,

Error in if (a == b) x[h] = i : missing value where TRUE/FALSE needed

Please do not provide me with alternate direct methods. I need help in improving the function that I have written. As I am modifying the attributes of a shapefile imported in R. It will help me improve my understanding.

Aucun commentaire:

Enregistrer un commentaire