简体   繁体   English

如何将R数据帧中的特殊值转换为NA?

[英]How to convert special value in R data-frame to NA?

I have a data-frame containing # as a missing value in multiple columns. 我有一个data-frame其中包含#作为多列中的缺失值。 How can I convert all such # s to NA s? 如何将所有此类#转换为NA

You can do this a few ways. 您可以通过几种方法来执行此操作。 One is to re-read the file in with the na.strings argument set to "#" 一种方法是将na.strings参数设置为"#"以重新读取文件

read.table(file, na.strings = "#")

Another would be to just change the values in the data frame df with 另一方法是仅使用以下命令更改数据帧df的值

df[df == "#"] <- NA

I have written a function makemeNA that is part of my "SOfun" package . 我已经写了一个函数makemeNA ,它是我的“ SOfun”包的一部分

The function looks like this (in case you don't want to get the package just for this function): 该函数看起来像这样(如果您不想仅为此函数获取软件包):

makemeNA <- function (mydf, NAStrings, fixed = TRUE) {
  if (!isTRUE(fixed)) {
    mydf[] <- lapply(mydf, function(x) gsub(NAStrings, "", x))
    NAStrings <- ""
  }
  mydf[] <- lapply(mydf, function(x) type.convert(
    as.character(x), na.strings = NAStrings))
  mydf
}

Usage would be: 用法是:

makemeNA(df, "#")

Get the package with: 通过以下方式获取软件包:

library(devtools)
install_github("mrdwab/SOfun")
is.na(dat) <- dat == "#"

可以解决问题(其中dat是数据框的名称)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在R中将列表转换为数据帧 - How to convert a list to a data-frame in r 如何在r中堆叠数据帧的列? - How to stack columns of data-frame in r? 在R中将单个响应数据框架转换为团队级数据框架 - convert individual response data-frame into team-level data-frame in r 如何将带有NA项的lapply的结果转换为R中的数据帧? - How to convert the result of lapply with NA items to a data frame in R? 如何使用在r中重复的另一个数据框中的特定列更新数据框中的新列? - How to update new column in data-frame with specific column from another data-frame with duplicated in r? 如何编写一个R函数来计算数据框中的表达式 - How to write an R function that evaluates an expression within a data-frame 如何在r中堆叠数据框列并合并列? - How to stack columns of data-frame and merge columns in r? 如何将特定的“NA”值(并非全部为“NA”)替换为 R 数据框中的特定数值? - How to replace the specific 'NA' value (not all 'NA') to the specific numerical value in R data frame? R识别数据框中的第一个值,并通过从新列的数据框中的所有值中添加/减去该值来创建新变量 - R identifying first value in data-frame and creating new variable by adding/subtracting this from all values in data-frame in new column R中的NA数据帧 - Data frame with NA in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM