exAres
exAres

Reputation: 4926

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

I have a data-frame containing # as a missing value in multiple columns. How can I convert all such #s to NAs?

Upvotes: 0

Views: 134

Answers (3)

Sven Hohenstein
Sven Hohenstein

Reputation: 81733

is.na(dat) <- dat == "#"

will do the trick (where dat is the name of your data frame).

Upvotes: 3

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193667

I have written a function makemeNA that is part of my "SOfun" package.

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")

Upvotes: 2

Rich Scriven
Rich Scriven

Reputation: 99361

You can do this a few ways. One is to re-read the file in with the na.strings argument set to "#"

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

Another would be to just change the values in the data frame df with

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

Upvotes: 2

Related Questions