根据R中的条件语句替换以下n个元素

时间:2017-12-19 16:46:52

标签: r for-loop if-statement

我正在尝试基于条件语句替换元素。例如

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"

我想找到一种简单的方法来做,因为我需要替换我的数据帧中的90个元素。所以我尝试了下面没有给出所需输出的内容。

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"  

非常感谢您的任何帮助或建议。

2 个答案:

答案 0 :(得分:2)

您可以通过以下方式修改代码:

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

答案 1 :(得分:1)

一种选择是以这种方式使用:

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"
  }
}