2017-02-10 94 views
0

我在互聯網上發現了多個帖子,但是我仍然無法將「?」如我的老師所問,值爲「-1」。這是我的代碼:替換data.frame的值

>library(e1071); 

>mammogram <- data.frame 

>mammogram.frame = read.table("https://archive.ics.uci.edu/ml/machine-learning-databases/mammographic-masses/mammographic_masses.data", 
      sep=",", 
      col.names=c("Birads","Age","Shape","Margin","Density","Severity"), 
      fill=TRUE, 
      strip.white=TRUE) 

>mammogram.frame[which(mammogram.frame=="?")]<-"-1" 

>mammogram.frame 

>summary(mammogram.frame) 

>svm.model <- svm(Density~., 
    data=mammogram.frame, 
    type="C-classification", 
    cost=1.0, 
    kernel="polynomial", 
    degree=2.0) 
>svm.model 

,當我運行的代碼中,mammogram.frame[which(mammogram.frame=="?")]<-"-1"返回以下的輸出:

> mammogram.frame[which(mammogram.frame=="?")]<-"-1" 
Error in `[<-.data.frame`(`*tmp*`, which(mammogram.frame == "?"), value = "-1") : 
    new columns would leave holes after existing columns 

我也嘗試下面的代碼,但它在別的變換我的數據?

> mammogram.frame <- as.character(mammogram.frame) 
> mammogram.frame[mammogram.frame == "?"] <- "-1" 

> mammogram.frame 
[1] "c(6, 5, 6, 5, 6, 5, 5, ...) 

> mammogram.frame <- as.factor(mammogram.frame) 
> mammogram.frame 
[1] c(6, 5, 6, 5, 6, 5, 5, ...) 

我的意思是說,它並沒有給我相同的視覺作爲一開始的時候我跑>mammogram.frame ..

任何想法通過「?」值爲-1?因爲它在我的工作>mammogram.frame[which(mammogram.frame=="?")] <- NA

謝謝!

回答

0

請嘗試以下變化時,負載:

mammogram.frame = read.table("https://archive.ics.uci.edu/ml/machine-learning-databases/mammographic-masses/mammographic_masses.data", 
          sep=",", 
          col.names=c("Birads","Age","Shape","Margin","Density","Severity"), 
          fill=TRUE, 
          strip.white=TRUE, 
          stringsAsFactors = F) 

然後執行:

mammogram.frame[mammogram.frame=="?"] = "-1" 

結果:

> head(mammogram.frame) 
    Birads Age Shape Margin Density Severity 
1  5 67  3  5  3  1 
2  4 43  1  1  -1  1 
3  5 58  4  5  3  1 
4  4 28  1  1  3  0 
5  5 74  1  5  -1  1 
6  4 65  1  -1  3  0