for循环出错

时间:2013-04-05 12:10:48

标签: r

k<-21;

for(i in 5:k)
{
pharma[,i][pharma[,i]=="#N/A"]<- NA
pharma[,i][pharma[,i]=="NM"]<- NA
num<-sum(is.na(pharma[,i]))
n=1-num/length(pharma[,i])

if(n<0.8) {
rm(pharma[,i])
Else n=0
}
}

基本上尝试用NA替换列并删除NA过多的列。

2 个答案:

答案 0 :(得分:2)

您没有告诉我们代码创建的错误。但有几点意见:

  • R区分大小写。 Elseelse不同,Else不正确
  • 您不会在if
  • 之前关闭else声明
  • 无需明确循环列

答案 1 :(得分:1)

你可能想要 之类的东西

## extract the columns to manipulate
pp <- pharma[,5:21]
## set relevant values to NA
pp <- lapply(pp,function(x) x[x %in% c("#N/A","NM")] <- NA)
## estimate fraction NA and test
badcols <- colMeans(is.na(pp))>0.2
## remove bad columns
pp <- pp[,!badcols]
## put the manipulated stuff back together with the original structure
pharma <- cbind(pharma[,1:4],pp)

但如果没有可重复的例子,很难说清楚。