我试图基于条件语句替换元素。例如
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"
非常感谢您的任何帮助或建议。
您可以通过以下方式修改代码:
for(i in 1:length(df)){
if (df[i]=="b"){
df[i+1:3]<-"N"
}
}
一种选择是以这种方式使用:
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"
}
}