【发布时间】:2020-04-25 15:21:13
【问题描述】:
我有一个input data.frame,其中包含两个不需要的元素(即"#N/A",'p')。我用NA 清理和替换元素。
然后,我删除所有带有 NA 的行,以获得一个完全干净的 data.frame,其中第一列 (id) 和最后一列 (read_2018) 仅包含数字。
问题: 为什么id 和read_2018 仍然是一个因素?如何以 FUNCTIONAL 方式(例如,使用 loop)为任何 data.frame 自动修复此问题?!
也就是说,在完全清理之后,我希望任何由所有数字组成的列都变成类数字,任何所有字符都变成类字符等等?
input <- data.frame(id = c(1,"#N/A",3, 4), school = LETTERS[1:4], read_2018 =c("#N/A",'p',9, 8))
sapply(input, class) ## check class of all columns
#> id school read_2018
#> "factor" "factor" "factor"
replace = c("#N/A", 'p') # Unwanted elements to be replaced
with = NA # with `NA`
input[sapply(input, `%in%`, replace)] <- with ## Now replace unwanted elements with `NA`
input <- na.omit(input) ## Remove all rows with `NA`
sapply(input, class) ## class of clean `input` without `NA` or character elements
#> id school read_2018 ###@@@ WHY STILL class of id and read_2018 is factor? How to fix?!
#> "factor" "factor" "factor"
【问题讨论】:
-
@akrun,有人建议关闭问题,以避免对你我投反对票,我删除了问题!