Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: removing NAs in numerical vectors

Tags:

r

I am an R novice and am having some challenges. I am dealing with a large dataframe which I have read from a csv file. My numerical vectors contain NAs which are stopping me from running analyses. How do I get rid of these NAs so I can actually do something with my data?

like image 355
Greg Avatar asked Jun 29 '10 22:06

Greg


People also ask

How do I remove a nan from a vector in R?

omit() method is used to remove the NA values directly by resulting in the non-NA values and omitted NA values indexes. Return type: Returns the non-NA values. Returns the indexes of NA values which are removed from the vector.

How do I get rid of NAs in R?

To remove all rows having NA, we can use na. omit function. For Example, if we have a data frame called df that contains some NA values then we can remove all rows that contains at least one NA by using the command na. omit(df).

How do I remove NAs from a column in R?

To remove observations with missing values in at least one column, you can use the na. omit() function. The na. omit() function in the R language inspects all columns from a data frame and drops rows that have NA's in one or more columns.

How do I replace NAs with 0 in R?

To replace NA with 0 in an R data frame, use is.na() function and then select all those values with NA and assign them to 0. myDataframe is the data frame in which you would like replace all NAs with 0.


2 Answers

  • for particular variable: x[!is.na(x)], or na.omit (see apropos("^na\\.") for all available na. functions),
  • within function, pass na.rm = TRUE as an argument e.g. sapply(dtf, sd, na.rm = TRUE),
  • set global NA action: options(na.action = "na.omit") which is set by default, but many functions don't rely on globally defined NA action (mean for instance), while some do (right now I cannot come up with an example),
  • and, of, course, if you have a lot of NA's, you should consider variable imputation, there's a question asked on SO that can be helpful.

Long story short, dealing with NA's is a very broad problem, try to concretize it a bit and give us a concise question. I'm sure that someone of SOers can help you!

Cheers, lad!

like image 84
aL3xa Avatar answered Oct 02 '22 11:10

aL3xa


na.omit(dataFrame)

This is an awesome website that I use for quick R related information: http://www.statmethods.net/input/missingdata.html

like image 21
Dave Avatar answered Oct 02 '22 11:10

Dave