子集化数据帧删除错误值

时间:2015-03-03 16:05:12

标签: r

我有以下数据:

head(df)

enter image description here

有时候我在答案栏中有“Nan”的价值。 enter image description here

我想要做的是为所有行创建一个单独的数据框,其中包含此值,而不是。

我使用了以下代码:

dfwith <-df[ !grepl("Nan", df$answer) , ]
dfwithout <-df[ grepl("Nan", df$answer) , ]

但是我的结果不正确,我不明白为什么,我哪里出错了。 提前致谢。请帮忙。

编辑:

> dput(droplevels(head(df)))
structure(list(X.run.number. = c(16L, 9L, 3L, 18L, 1L, 19L), 
    density = c(0.52, 0.52, 0.52, 0.52, 0.52, 0.52), k = c(100L, 
    100L, 100L, 100L, 100L, 100L), knt = c(2900L, 1700L, 500L, 
    2900L, 500L, 2900L), threshold = c(0.2, 0.2, 0.3, 0.4, 0.1, 
    0.5), X.step. = c(0L, 0L, 0L, 0L, 0L, 0L), answer = structure(c(4L, 
    5L, 1L, 6L, 2L, 3L), .Label = c("100.2767857", "106.9588889", 
    "107.1467647", "53.13833333", "64.54785714", "95.61115385"
    ), class = "factor"), percent = c(16.04938272, 18.51851852, 
    38.27160494, 34.56790123, 11.11111111, 45.67901235)), .Names = c("X.run.number.", 
"density", "k", "knt", "threshold", "X.step.", "answer", "percent"
), row.names = c(NA, 6L), class = "data.frame")

编辑2:

> dput(droplevels(tail(df)))
structure(list(X.run.number. = c(4488L, 4509L, 4502L, 4537L, 
4530L, 4544L), density = c(0.52, 0.52, 0.52, 0.52, 0.52, 0.52
), k = c(600L, 600L, 600L, 600L, 600L, 600L), knt = c(19700L, 
23300L, 22100L, 28100L, 26900L, 29300L), threshold = c(0.1, 0.1, 
0.1, 0.1, 0.1, 0.1), X.step. = c(0L, 0L, 0L, 0L, 0L, 0L), answer = structure(c(1L, 
1L, 1L, 1L, 1L, 1L), .Label = "\"Nan\"", class = "factor"), percent = c(11.11111111, 
12.34567901, 6.172839506, 8.641975309, 11.11111111, 11.11111111
)), .Names = c("X.run.number.", "density", "k", "knt", "threshold", 
"X.step.", "answer", "percent"), row.names = 4545:4550, class = "data.frame")

2 个答案:

答案 0 :(得分:1)

仅获取没有NA的行,您可以使用:

dfwithout <- na.omit(df)

如果您需要将Nan更改为NA或NaN,您可以使用:

df <- gsub("Nan", "NA", df)

您可以看到哪些行和列具有NA:

which(is.na(df), arr.ind=TRUE)

答案 1 :(得分:1)

我认为这与你有NaN而不是NA有关。试试这个。

df[complete.cases(df), ]