Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R is.na() Function - Detecting and Handling Missing Values

R is.na() Function - Detecting and Handling Missing Values

R Language Examples R Language Examples

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:

Example

Detect NA in a vector

x

<-

c

(

10

, NA,

20

, NA,

30

,

40

)

print

(

"NA detection:"

)

print

(

is.na

(

x

)

)

print

(

paste

(

"Number of NAs:"

,

sum

(

is.na

(

x

)

)

)

)

print

(

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

)

)

print

(

"\nData frame:"

)

print

(

df

)

Find complete rows (without NA)

print

(

"Complete rows:"

)

print

(

df

[

complete.cases

(

df

)

,

]

)

Count the number of NAs in each column

print

(

"Number of NAs per column:"

)

print

(

colSums

(

is.na

(

df

)

)

)

Remove rows containing NA

df_clean

<-

na.omit

(

df

)

print

(

"\nAfter removing NA:"

)

print

(

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 R Language Examples