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

问题描述 投票:2回答:2

我试图基于条件语句替换元素。例如

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"  

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

r for-loop if-statement
2个回答
2
投票

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

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

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"
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.