替换data.frame

时间:2017-02-10 05:23:37

标签: r dataframe

我在互联网上发现了多个帖子,但是我仍然无法重新编写“?”我的老师要求“-1”的值。这是我的代码:

>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

时起作用

谢谢!

1 个答案:

答案 0 :(得分: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