R is.na() Function - Detecting and Handling Missing Values
The R is.na() function is used to detect which elements in a vector or data frame are missing values NA.
Handling missing values is an essential step in data analysis, directly affecting the accuracy of the analysis results.
The syntax of the is.na() function is as follows:
is.na(x)
anyNA(x) # 检查是否存在任何 NA
complete.cases(x) # 检查哪些行没有 NA
Parameter Description:
-
x The vector, matrix, or data frame to check.
Example
Detect NA in a vector
x
<-
c
(
10
, NA,
20
, NA,
30
,
40
)
(
"NA detection:"
)
(
is.na
(
x
)
)
(
paste
(
"Number of NAs:"
,
sum
(
is.na
(
x
)
)
)
)
(
paste
(
"Whether there is NA:"
, anyNA
(
x
)
)
)
Handle NA in a data frame
df
<-
data.frame
(
Name
=
c
(
"Zhang San"
,
"Li Si"
,
"Wang Wu"
,
"Zhao Liu"
)
,
Score
=
c
(
88
, NA,
76
, NA
)
,
Age
=
c
(
25
,
30
, NA,
28
)
)
(
"\nData frame:"
)
(
df
)
Find complete rows (without NA)
(
"Complete rows:"
)
(
df
[
complete.cases
(
df
)
,
]
)
Count the number of NAs in each column
(
"Number of NAs per column:"
)
(
colSums
(
is.na
(
df
)
)
)
Remove rows containing NA
df_clean
<-
na.omit
(
df
)
(
"\nAfter removing NA:"
)
(
df_clean
)
The output of the code above is:
[1] "NA 检测:"
[1] FALSE TRUE FALSE TRUE FALSE FALSE
[1] "NA 个数: 2"
[1] "是否有 NA: TRUE"
[1] "数据框:"
姓名 成绩 年龄
1 张三 88 25
2 李四 NA 30
3 王五 76 NA
4 赵六 NA 28
[1] "完整行:"
姓名 成绩 年龄
1 张三 88 25
[1] "每列 NA 数:"
姓名 成绩 年龄
0 2 1
[1] "删除 NA 后:"
姓名 成绩 年龄
1 张三 88 25
R Language Examples