Home > Net >  How to write a loop that select values containing a pattern and modifies them in r
How to write a loop that select values containing a pattern and modifies them in r

Time:10-09

I am trying to write a loop that, given a list of indices "list_idx" of the values that contain a certain pattern, say "P", does the following:

1)Iterates over a column of the dataset 2) For all elements in the column, if their index belongs to list_idx, does the following:

  • It removes the pattern "P" from the value,
  • It converts the value to an integer,
  • It multiplies the number obtained per 100.

I am stuck at the beginning of the second part. Any suggestion? Thanks in advance for your help!

I tried:

for (i in list_idx){
    Dataset$column[i] <- str_remove(Dataset$column, "K")
    Dataset$column[i] <- (as.integer(Dataset$column[i]))*100}

and I get as error:

"number of items to replace is not a multiple of replacement lengthnumber of items to replace is not a multiple of replacement lengthnumber of items to replace is not a multiple of replacement lengthnumber of items to replace is not a multiple of replacement lengthnumber of items to replace is not a multiple of replacement lengthnumber of items to replace is not a multiple of replacement lengthnumber of items to replace is not a multiple of replacement lengthnumber of items to replace is not a multiple of replacement lengthnumber of items to replace is not a multiple of replacement lengthnumber of items..."

CodePudding user response:

We may not need to loop here i.e. str_remove is vectorized and it doesn't need to loop over each element of the 'column'. Instead, we can subset the 'column' based on the index in 'list_idx', remove the "K", convert to integer, multiply by 100 and update it back

library(stringr)
Dataset$column[list_idx] <- as.integer(str_remove(Dataset$column[list_idx], "K")) * 100
  • Related