mardi 19 décembre 2017

Replace following n elements based on a conditional statement in R

I am trying to replace elements based on a conditional statement. For example

df=c(1,2,"b","b",1,2,2,"b",2,1,2,2,"b",1,1,2)
for(i in 1:length(df)){
 if (df[i]=="b"){
  df[i+1]="N"
  df[i+2]="N"
  df[i+3]="N"
 }
}
df
[1] "1" "2" "b" "N" "N" "N" "2" "b" "N" "N" "N" "2" "b" "N" "N" "N"

I want to find a simple way to do it becasue I need replace following 90 elements in my dataframe. So I've tried the below which doesn't give the desired output.

n=3
for(i in 1:length(df)){
  if (df[i]=="b"){df[i+1:i+n]="N"}
}
df
[1] "1" "2" "b" "b" "1" "2" "N" "N" "N" "N" "N" "2" "b" "1" "1" "2" "N"  "N" "N" "N" "N" "N" "N" "N" "N" "N" "N" "N" "N"  

Thank you very much for any help or suggestion.

Aucun commentaire:

Enregistrer un commentaire