如何:
> df
# c1 c2 c3
# 1 yes yes no
# 2 no ok yes
# 3 ok no ok
# 4 yes yes no
# 5 no ok yes
# 6 ok no ok
# 7 yes yes no
# 8 no ok yes
# 9 ok no ok
toRemove <- "no"
data.frame(lapply(df,
function(x) factor(as.character(x), levels=levels(x)[levels(x)!=toRemove])))
# c1 c2 c3
# 1 yes yes <NA>
# 2 <NA> ok yes
# 3 ok <NA> ok
# 4 yes yes <NA>
# 5 <NA> ok yes
# 6 ok <NA> ok
# 7 yes yes <NA>
# 8 <NA> ok yes
# 9 ok <NA> ok
玩具數據
df <- structure(list(c1 = structure(c(3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L,
2L), .Label = c("no", "ok", "yes"), class = "factor"), c2 = structure(c(3L,
2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L), .Label = c("no", "ok", "yes"
), class = "factor"), c3 = structure(c(1L, 3L, 2L, 1L, 3L, 2L,
1L, 3L, 2L), .Label = c("no", "ok", "yes"), class = "factor")), .Names = c("c1",
"c2", "c3"), row.names = c(NA, -9L), class = "data.frame")
這不是一個直接的ANS但請考慮在你的情況下是否使用「水滴」。如果是這樣,你的代碼簡化爲'lapply(fact,droplevels)'。 –
@KonradRudolph,在這種情況下,他們可以使用'droplevels(fact)' –
Konrad指出,你的問題並不清楚。你是否希望以「否」作爲答案來放棄觀察,或者是否已經放棄觀察,並且只是想從因子水平中去除這個水平? – lmo