【问题标题】:class not changing in data.frame after NA cleaning in R在 R 中进行 NA 清理后,类在 data.frame 中没有变化
【发布时间】:2020-04-25 15:21:13
【问题描述】:

我有一个input data.frame,其中包含两个不需要的元素(即"#N/A",'p')。我用NA 清理和替换元素。

然后,我删除所有带有 NA 的行,以获得一个完全干净的 data.frame,其中第一列 (id) 和最后一列 (read_2018) 仅包含数字。

问题: 为什么idread_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,有人建议关闭问题,以避免对你我投反对票,我删除了问题!

标签: r dataframe class lapply


【解决方案1】:

一旦您删除了任何不需要的数据,类就不会自动更改。

您可以使用type.convert 将数据转换为适当的类。

input <- type.convert(input, as.is = TRUE)
sapply(input, class)

#        id      school   read_2018 
#  "integer" "character"   "integer" 

【讨论】:

  • class(data) 是什么?
  • 我猜数据中有一些列具有不同的类。将其更改为一个普通类。使用data[] &lt;- lapply(data, as.character),然后试试上面的,
【解决方案2】:

我们可以使用map来获取类

input <- type.convert(input, as.is = TRUE)

如果我们有 R 的早期版本,即 R 版本

input[] <- lapply(input, function(x) type.convert(as.character(x), as.is = TRUE))

然后使用map,得到class

library(purrr)
map_chr(input, class)

或者在base Rlapplyunlist

unlist(lapply(input, class))

【讨论】:

  • @rnorouzian 让我检查一下
  • @rnorouzian 它对我来说工作正常str(type.convert(input, as.is = TRUE))# 'data.frame': 3837 obs. of 11 variables: $ stid : int 300365 300365 300365 300437 300437 300437 300475 300530 300942 300942 ... $ scid : chr "Carmichael" "Carmichael" "Carmichael" "Johnson" ... $ group : chr "T" "T" "T" "C" ... $ gender : chr "Female" "Female" "Female" "Female" ... $ ethnicity: chr "Afamerican" "Afamerican" "Afamerican" "Hispanic" ... $ LEP : chr "None" "None" "None" "LEP" ...
  • @rnorouzian 你可以查看R version。我有 R 3.6.2
  • @rnorouzian 如果你有以前的 R 版本,请做 input[] &lt;- lapply(input, function(x) type.convert(as.character(x), as.is = TRUE)) 我认为 type.convert for data.frame 方法仅在最近的版本中添加(希望我没有错)跨度>
  • @rnorouzian 在这种情况下,使用lapply 方式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-30
  • 1970-01-01
  • 1970-01-01
  • 2013-07-28
  • 1970-01-01
  • 2019-09-28
  • 1970-01-01
相关资源
最近更新 更多