JaneZ
JaneZ

Reputation: 23

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.

Upvotes: 2

Views: 42

Answers (2)

MKR
MKR

Reputation: 20085

One option is to use in this way:

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):(i+3)] <- "N"
  }
}

Upvotes: 1

mtoto
mtoto

Reputation: 24178

You can modify your code in the following way:

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

Upvotes: 2

Related Questions