How to Use na.rm in R?
Last Updated :
01 Feb, 2022
In this article, we will discuss how to use na.rm in R Programming Language. na.rm in R is used to remove the NA values.
na.rm in vector
When we perform any operation, we have to exclude NA values, otherwise, the result would be NA.
Syntax: function(vector,na.rm)
where
- vector is input vector
- na.rm is to remove NA values
- function is to perform operation on vector like sum ,mean ,min ,max etc
Example 1: In this example, we are calculating the mean, sum, minimum, maximum, and standard deviation with NA
R
data = c (1,2,3, NA ,45,34, NA , NA ,23)
print (data)
print ( mean (data,na.rm= FALSE ))
print ( sum (data,na.rm= FALSE ))
print ( min (data,na.rm= FALSE ))
print ( max (data,na.rm= FALSE ))
print ( sd (data,na.rm= FALSE ))
|
Output:
[1] 1 2 3 NA 45 34 NA NA 23
[1] NA
[1] NA
[1] NA
[1] NA
[1] NA
Example 2: In this example, we are calculating the mean, sum, minimum, maximum, and standard deviation without NA
R
data = c (1,2,3, NA ,45,34, NA , NA ,23)
print (data)
print ( mean (data,na.rm= TRUE ))
print ( sum (data,na.rm= TRUE ))
print ( min (data,na.rm= TRUE ))
print ( max (data,na.rm= TRUE ))
print ( sd (data,na.rm= TRUE ))
|
Output:
[1] 1 2 3 NA 45 34 NA NA 23
[1] 18
[1] 108
[1] 1
[1] 45
[1] 18.86796
na.rm in dataframe
We have to use apply function to apply the function on the dataframe with na.rm function
Syntax: apply(dataframe, 2, function, na.rm )
where
- dataframe is the input dataframe
- function is to perform some operations like mean,min ,max etc
- 2 represents column
- na.rm is to remove NA values
Example 1: In this example, we are calculating the mean, sum, minimum, maximum, and standard deviation without NA in all columns
R
data = data.frame (column1 = c (1,2, NA ,34),
column2 = c ( NA ,34,56, NA ),
column3 = c ( NA , NA ,32,56))
print (data)
apply (data, 2, mean , na.rm = FALSE )
apply (data, 2, sum , na.rm = FALSE )
apply (data, 2, min, na.rm = FALSE )
apply (data, 2, max , na.rm = FALSE )
apply (data, 2, sd, na.rm = FALSE )
|
Output:
Example 2: Excluding NA values
R
data = data.frame (column1 = c (1,2, NA ,34),
column2 = c ( NA ,34,56, NA ),
column3 = c ( NA , NA ,32,56))
print (data)
apply (data, 2, mean , na.rm = TRUE )
apply (data, 2, sum , na.rm = TRUE )
apply (data, 2, min, na.rm = TRUE )
apply (data, 2, max , na.rm = TRUE )
apply (data, 2, sd, na.rm = TRUE )
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...